How to check if a variable is an Enum

  • Thread starter Thread starter Patrick B
  • Start date Start date
P

Patrick B

Is there a way to check if a certain variable is an enum?

Example code:

public enum MyEnum {
Monday,
Tuesday,
Wednesday
}
public void MyMethod()
{
MyEnum myEnum = MyEnum.Monday;
string myString = "Bla bla bla";
bool firstTry = IsEnum(myEnum);
bool secondTry = IsEnum(myString);
}

Is there a way to write a function IsEnum() so that firstTry is true and
secondTry is false?

myEnum.GetType() tells me that myEnum is of the type MyEnum.
GetTypeCode() tells me that it's an Int32.

Thanks,

-Patrick
 
Patrick,

My guess is that you can check the inheritance chain for the type in
question - it should have System.Enum in the chain.
 
Roland,

Is there a way to use IsDefined even if I don't have a myValue to check
against it? I don't want to check if myValue is defined, I want to check
if the Enum itself is defined.

Thanks,

Patrick
 
Hi Patrick,

maybe I don't see your problem, so let as face the situation



Example code:

public enum MyEnum {
Monday,
Tuesday,
Wednesday
}

public void MyMethod()
{
MyEnum myEnum = MyEnum.Monday;
#
# if MyEnum is never defined, the compiler generates an error! So I assume
MyEnum IS DEFINED!
#


string myString = "Bla bla bla";
bool firstTry = Enum.IsDefined(typeof(MyEnum), myEnum);
# true - cause of myEnum is member of MyEnum

bool secondTry = Enum.IsDefined(typeof(MyEnum), myString);
# false - myString isn't member MyEnum
}

Is it what you want to know?

Roland
 
Hi,

bool a = false;
try
{
Enum b = (Enum) value_to_check;
a = true;
}
catch{}

Not very elegant, but ... functional :D

Cheers,
 
Aha! Yes, that clears it up.

I knew you could use IsDefined like this:

bool secondTry = Enum.IsDefined(typeof(MyEnum), myString);

But I didn't know you could use it like this:

bool firstTry = Enum.IsDefined(typeof(MyEnum), myEnum);

So it seems that you are telling me that I should be able to write my
IsEnum function like this:

bool IsEnum(object o)
{
return Enum.IsDefined(typeof (o), o);
}
 
sorry, I meant to reply to your original post.

don't use Enum.IsDefined, it tests for something completely different, and
is not what you want.
 
The IsEnum() method on the Type object should solve your problem.

bool firstTry = myEnum.GetType().IsEnum();
bool secondTry = myString.GetType().IsEnum();
 
Back
Top