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)));
}
You can also check by using property IsEnum
on Type
:
Type t = typeof(DayOfWeek);
bool isEnum = t.IsEnum;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With