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?
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.
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 * .
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.
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.
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.
When I did profiling, Enum.GetHashCode took a lot of cycles. I was able to improve it by using (int)Enum where possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With