What are the rules I should follow to ensure GetHashCode() method returns unique value for an object?
For example:
You shouldn't even aim for GetHashCode()
returning a unique value for each object. That's not the point of GetHashCode()
.
Eric Lippert has a great post about hash codes which you should read thoroughly. Basically you want to end up with something which will always return the same value for two equal objects (and you need to work out what you mean by equal) and is likely to return different values for two non-equal objects.
Personally I tend to use an implementation like this:
public override int GetHashCode()
{
int hash = 17;
hash = hash * 31 + field1.GetHashCode();
hash = hash * 31 + field2.GetHashCode();
hash = hash * 31 + field3.GetHashCode();
...
return hash;
}
Things to watch out for:
If your fields can be null, you need to check for that while calculating your hash. For example:
hash = hash * 31 + (field2 == null ? 0 : field2.GetHashCode());