Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GetHashCode for getting Enum int value

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?

like image 883
Mohit Vashistha Avatar asked Jan 03 '11 13:01

Mohit Vashistha


People also ask

How do you find the value of an enum?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

Are enums ints?

I recently explained that although both C and C++ provide void * as the generic data pointer type, each language treats the type a little differently. For any object type T , both C and C++ let you implicitly convert an object of type T * to void * .

Can enums contain numbers?

Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.

Can an enum have one value?

With an enum type with only one value, most developers will not expect that (UserIDEnum)42 is used, since it's not a "defined" value of the enum.


2 Answers

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.

like image 135
CodesInChaos Avatar answered Sep 26 '22 11:09

CodesInChaos


When I did profiling, Enum.GetHashCode took a lot of cycles. I was able to improve it by using (int)Enum where possible.

like image 33
Vijay Vepakomma Avatar answered Sep 24 '22 11:09

Vijay Vepakomma