Aran Mulholland
Aran Mulholland

Reputation: 23935

Test if an object is an Enum

I would like to know if 'theObject' is an enum (of any enum type)

 foreach (var item in Enum.GetValues(theObject.GetType())) {

     //do something
 }

Upvotes: 105

Views: 48509

Answers (4)

bugged87
bugged87

Reputation: 3142

For generic type parameters, the parameter can be constrained rather than tested:

where T : Enum

Upvotes: 6

Chris Schmich
Chris Schmich

Reputation: 29466

If you have a Type, use the Type.IsEnum property, e.g.:

bool isEnum = theObject.GetType().IsEnum;

Upvotes: 76

Laramie
Laramie

Reputation: 5587

just use

if (theObject is Enum)
 //is an enum

Upvotes: 10

EMP
EMP

Reputation: 61971

The question is the answer. :)

bool isEnum = theObject is Enum;

Upvotes: 234

Related Questions