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)