Using GetHashCode for getting Enum int value

Mohit Vashistha picture Mohit Vashistha · Jan 3, 2011 · Viewed 21.4k times · Source

I have an enum

public enum INFLOW_SEARCH_ON
{
  ON_ENTITY_HANDLE = 0,         
  ON_LABEL = 1,                 
  ON_NODE_HANDLE = 2            
} // enum INFLOW_SEARCH_ON

I have to use this enum for searching in a grid column.

To get the column index I am using

  MyEnumVariable.GetHashCode() 

Which works ok, or should I use

  (short)MyEnumVariable

I am a bit confused over using GetHashCode(). Is there any problem using that?

Answer

CodesInChaos picture CodesInChaos · Jan 3, 2011

Using GetHashCode() is incorrect. You should cast to int. Using it the way you do is asking for raptors(or Raymond) to come and eat you.

That GetHashCode() happens to return the integer value of the enum is an implementation detail and may change in future versions of .net.

GetHashCode() guarantees that if two values are equal their hash codes are equal too. The other way round is not guaranteed.

My rule of thumb is that if GetHashCode were to return a constant value your program should still work correctly (but potentially be much slower) since a constant GetHashCode trivially fulfills the contract, but has bad distribution properties.