Is there a way to check if a type is an enumeration type?

Someone gives me type t.

I would like to know if this type is an enumeration or not.

public bool IsEnumeration(Type t) { // Mystery Code. throw new NotImplementedException(); } public void IsEnumerationChecker() { Assert.IsTrue(IsEnumeration(typeof(Color))); Assert.IsFalse(IsEnumeration(typeof(float))); } 
+4
source share
2 answers

You can also check using the IsEnum property in Type :

 Type t = typeof(DayOfWeek); bool isEnum = t.IsEnum; 
+10
source

There are various ways to achieve this goal:

 return typeof(Enum).IsAssignableFrom(t) && t != typeof(Enum); 

or

 return typeof(Enum).IsAssignableFrom(t) && t.IsValueType; 

or (now that I saw it exists by checking IsValueType )

 return t.IsEnum; 

Obviously, the latter is the best approach, but the first two will tell you how to handle such situations.

+3
source

Source: https://habr.com/ru/post/1336365/


All Articles