Search code examples
c#gethashcode

Overwriting GetHashCode (Enum plus Integer comparison)


I want to overwrite a GetHashCode method with following code:

public override int GetHashCode()
{
    var magicNumber1 = 5;
    var magicNumber2 = 3;

    return intType * magicNumber1 + 
          (int)enumType * magicNumber2;
}

Is this a proper way of returning GetHashCode when one value is Integer and second an Enum?


Solution

  • Well, you current implementation is quite OK, but you can be better off if intType and enumType are of small range. Suppose, intType (allmost always) is in the [0..1000000] and enumType is in the [0..10] range then

       public override int GetHashCode() {
          return unchecked(intType * 10 + (int)enumType);
       }
    

    will be a better choice: many hash collisions that a present in your current code are not such in the code above. For instance

       intType | enumType | old hash | suggested
       -----------------------------------------
             0          5         15           5
             3          0         15          30  
    

    Edit: In your case (please, see comments)

    it should not be more than 100

    assuming that you don't have negative values, you can try

       public override int GetHashCode() {
         // * 128 == << 7 may be faster than * 100 at some systems 
         return unchecked(intType * 128 + (int)enumType);
       }
    

    and expect to have no collisions at all