Possible Duplicate:
Using GetHashCode for getting Enum int value
Is it safe to use GetHasCode to get a enumeration value like the code below:
myList.SelectedIndex = myEnumValue.GetHashCode()
Possible Duplicate:
Using GetHashCode for getting Enum int value
Is it safe to use GetHasCode to get a enumeration value like the code below:
myList.SelectedIndex = myEnumValue.GetHashCode()
No. The result isn't guaranteed to be unique or equivalent to the integral value of that enum value.
I think it is currently implemented to be the same as a cast to int. But that's an implementation detail and may change at any time.
The correct way is to cast to the underlying integral type:
myList.SelectedIndex = (int)myEnumValue;
In general, no. GetHashCode returns the underlying value for enums, most likely because enums are just integers under the covers. However, this is an implementation detail that might change in a later version of the framework.
Apart from that, remember that enums doesn't need to start from 0, and doesn't need to increment by exactly one for each value - in other words, there are a multitude of ways you could get into trouble with that code.
The correct way of getting the underlying value of an enum value is to cast it:
int underlyingValue = (int)enumValue;
Just remember that it still isn't ok to use that value for your SelectedIndex, unless you specifically know that the enum being used starts at 0 and increments by one.