5

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?

3
  • How exactly are you trying to cast? Commented Dec 22, 2010 at 12:44
  • 1
    @annakata I would guess (int)e, which gives "Cannot convert type 'System.Enum' to 'int'" Commented Dec 22, 2010 at 12:48
  • @annakata: Sorry I thought I am obvious. Marc is right. Commented Dec 22, 2010 at 13:02

3 Answers 3

13
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)

Sign up to request clarification or add additional context in comments.

Comments

7

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.

1 Comment

If the actual type of the Enum is known (e.g. Reflection.BindingFlags) one may cast to that and then simply use that as an integer or long value. That will work for enum types whose underlying type is no bigger than the type one is using.
0
Int32 intValue = (Int32)Enum.Parse(e.GetType(), e.ToString()); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.