Search code examples
c#nhibernategethashcode

C#: override GetHashCode, what does this code do?


Here's the code I found in the Nhibernate 3 Beginners Guide to override GetHashCode. I don't understand why it uses result * 397. If 397 just a random number he use to generate unique result??

Can we just GetHashCode for firstname, middlename and lastname, then combine it together using ^, it should also generate an unique result.

public override int GetHashCode()
{
   unchecked
   {
       var result = FirstName.GetHashCode();
       result = (result*397) ^ (MiddleName != null ? MiddleName.GetHashCode() : 0);
       result = (result*397) ^ LastName.GetHashCode();
       return result;
   }
}

Solution

  • Multiplying the intermediate hash code by a given number as part of each combination will mean the ordering of the combined has codes will not be irrelevant.

    If you just did an exclusive or on the three name parts, then "John William James" would give the same hash code as "James William John".

    397 is chosen because it is a prime number large enough sufficient to cause the hash code to overflow, and this helps generate a good distribution of hash codes.

    The overflow is the reason this code has to sit inside an unchecked block.