user420667
user420667

Reputation: 6710

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)));
}

Upvotes: 5

Views: 706

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503869

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.

Upvotes: 3

nan
nan

Reputation: 20316

You can also check by using property IsEnum on Type:

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

Upvotes: 10

Related Questions