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());
You don't necessarily need a fool proof hashcode because you also need to override Equals for comparison. Usually what I do is take the values I know are different across objects, concatenate them into a string and return the hash for that.
I think your answer is here: See Jon Skeet answer, generally pretty reliable way to calculate it. Proved by time :)
What is the best algorithm for an overridden System.Object.GetHashCode?
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.