Consider the following two enums:
enum MyEnum1 {
Value1 = 1,
Value2 = 2,
Value3 = 3
}
enum MyEnum2 {
Value1 = 'a',
Value2 = 'b',
Value3 = 'c'
}
I can retrieve the physical value represented by these enum values through explicit casting, ((int)MyEnum1.Value2) == 2 or ((char)MyEnum2.Value2) == 'b', but what if I want to get the char representation or the int representation without first knowing the type to cast to?
Is it possible to get the underlying value of an enum without a cast or is it at least programatically possible to determine the correct type of the underlying value?
The underlying value of both of those enums is
int. You’re just using the fact that there’s an implicit conversion fromchartointin the second case.For example, if you look at the second enum in Reflector, you’ll see something like this:
EDIT: If you want a different underlying type, you’ve got to specify it, e.g.
However, only
byte,sbyte,short,ushort,int,uint,long, andulongare valid underlying enum types.