Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing GetHashCode [duplicate]

Tags:

c#

Possible Duplicate:
What is the best algorithm for an overridden System.Object.GetHashCode?

What constitutes a good implementation of the GetHashCode method? I did some googling, and found some goodlines (MSDN) but it seems like the logic just manipulates two numbers stored as fields in the class. Is the actual logic this simple to implement this method?

like image 492
GurdeepS Avatar asked May 22 '10 22:05

GurdeepS


1 Answers

The minimum requirement is that the hash code should be the same for any given value. So, this implementation works, but the distribution is horrible:

public override int GetHashCode() {
  return 1;
}

To work best, the hash codes should consider all relevant data in the object and be as evenly distributed as possible within the integer range.

An implementation that does consider all members, but doesn't give very good distribution can be found in the System.Drawing.Point structure. It uses XOR to combine the bits in the members, which means that all points where X and Y are equal get the hash code zero:

public override int GetHashCode() {
  return this.X ^ this.Y;
}

One way to get a better distribution is to multiply a member by a prime number and add the next member, repeating as needed:

public override int GetHashCode() {
  return ((this.Value1 * 251) + this.Value2) * 251 + this.Value3;
}

The same method has been used in simple random generators, as it scatters the values pretty well.

like image 73
Guffa Avatar answered Sep 30 '22 13:09

Guffa