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?
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
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With