Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Enum to uint

Tags:

c#

enums

I'm writing a function that takes an Enum and casts it to uint. From what I've seen when casting to int, you have to cast it to an object first: (int) (object) myEnumValue. If you write (int) myEnumValue you get a compile time exception.

Now, when I tried to cast it to uint, I was expecting that (uint) (object) myEnumValue would be alright. It compiles nicely, but when run, it generates an InvalidCastException. So to get it to work, I've used

(uint) (int) (object) myEnumValue

I think it looks funny, so I'm quite happy, but why is it so?

Maybe it would have been more correct to ask why it is not possible to cast object to uint, but I'm interested in whether there is another way to go from an Enum to uint. Is there?

Edit:

The context is a function, something like this:

public static uint ToUInt (Enum e)
{
    return (uint) (int) (object) e;
}

Edit 2:

The best solution was as mentioned by thecoop:

Convert.ToUInt32(e)
like image 547
Jonatan Lindén Avatar asked Dec 06 '09 11:12

Jonatan Lindén


2 Answers

The (uint) (object) myEnum approach fails because, by default, C# enums use int as their underlying type, and an int is what they get turned into when they're boxed. The C# syntax makes it look like enums inherit from their underlying type (like enum MyEnum : uint).

You have to explicitly tell the compiler to unbox from object to int first, then do a numerical conversion from int to uint. (Even though the syntax is the same, unboxing from object to a value type is a different process from casting between int and uint.)

like image 86
Tim Robinson Avatar answered Sep 21 '22 10:09

Tim Robinson


From what I've seen when casting to int, you have to cast it to an object first: (int) (object) myEnum. If you write (int) myEnum you get a compile time exception.

Not true. You can directly cast an enum value to an integer type.

Now, when I tried to cast it to uint, I was expecting that (uint) (object) myEnum would be alright. It compiles nicely, but when run, it generates an InvalidCastException. So to get it to work, I've used: (uint) (int) (object) myEnum
I think it looks funny, so I'm quite happy, but why is it so?

When you cast an enum value to object, it'll be boxed as its underlying type, which is int by default. You cannot unbox a boxed value to any type other than its actual type directly. Even this will fail:

short s = 10;
object o = s;
int i = (int)o; // throws `InvalidCastException` while `int i = (int)s;` works.
like image 40
mmx Avatar answered Sep 19 '22 10:09

mmx