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 you have mutable objects, be careful! You shouldn't mutate an object after using it as the key in a hash map.
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());
String
are there? How many instances ofint
are there? What is the return type ofString.GetHashCode
? Do you see the problem? – Grit