Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to check that a type is a type of enumeration?

Somebody gives me a type t.

I'd like to know if that 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)));
}
like image 559
user420667 Avatar asked Jan 20 '11 18:01

user420667


2 Answers

You can also check by using property IsEnum on Type:

Type t = typeof(DayOfWeek);
bool isEnum = t.IsEnum;
like image 71
nan Avatar answered Nov 07 '22 12:11

nan


There are various ways you can achieve this:

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

or

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

or (now that I've seen it exists while checking IsValueType)

return t.IsEnum;

Obviously the latter is the best approach, but the first two will give you hints about how to handle similar situations.

like image 3
Jon Skeet Avatar answered Nov 07 '22 11:11

Jon Skeet