简体   繁体   中英

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;
   }
}

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.

Multiplication is also basically bit shift (exactly bit shift if * a power of 2), so it has that effect on the computed value here, but as to why precisely 397, well that is just how this paticular hash algorithm was written. Yes, other values, indeed more complex algorithms are often used as a hashing algorithm.

This is different from simply XORing 3 hashcodes together, and will result in far fewer 'hash collisions' - where 2 (or more) objects hash to the same value (something to be minimized if not avoided in a good hash function)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM