Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast an Enum to an int?

I have a function that accepts an Enum (The base class) as a parameter:

public void SomeFunction(Enum e);

However I can't for some reason cast it to int. I can get the name of the enumeration value but not it's integral representation.
I really don't care about the type of the enumeration, I just need the integral value. Should I pass an int instead? Or am I doing something wrong here?

like image 488
the_drow Avatar asked Dec 22 '10 12:12

the_drow


2 Answers

int i = Convert.ToInt32(e);

This will work regardless of the underlying storage of the enum, whereas the other solutions will throw an InvalidCastException if the enum is stored in anything other than int32 (say, a byte or short)

like image 76
thecoop Avatar answered Nov 02 '22 15:11

thecoop


Enum isn't actually an enum... confusing. It is a boxed copy of an enum; still, the following should work:

int i = (int)(object)e;

(this (object) cast doesn't add a box, since it is already boxed)

Note also that not all enums are based on int; this unboxing trick may fail for non-int enums.

like image 34
Marc Gravell Avatar answered Nov 02 '22 15:11

Marc Gravell