How to check if a variable is an Enum

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
 
D

Dmitriy Lapshin [C# / .NET MVP]

Patrick,

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

Patrick B

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
 
G

Guest

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
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

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

Not very elegant, but ... functional :D

Cheers,
 
P

Patrick B

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

Guest

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.
 
S

sadhu

The IsEnum() method on the Type object should solve your problem.

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top