0

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()
Community
  • 1
  • 1
Marcelo de Aguiar
  • 1,432
  • 12
  • 31
  • 2
    Safe in what sense? There *can't* be a guarantee that the values will be unique... after all, you could have an enum with an underlying type of `long`, with more than 2^32 values. – Jon Skeet Jun 15 '11 at 20:46
  • 1
    Looks neither safe nor sensible. Consider `(int) myEnumValue` – H H Jun 15 '11 at 20:46
  • 1
    Unless I misunderstand you: No, it isn't safe. The hashcode should provide a deterministic but unpredictable value in the entire range of int values, so you code seems very strange. What are you trying to achieve? – faester Jun 15 '11 at 20:47
  • Should have notices this is a duplicate considering that I posted in that other thread -_- – CodesInChaos Jun 15 '11 at 20:59

2 Answers2

1

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;
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1

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.

driis
  • 161,458
  • 45
  • 265
  • 341