How should good overriden GetHashCode
method look like? (for instance for a pure model class which contains three string properties) Are there any common principles / schemats in writing such methods? Where it is exactly used (besides HashTables/Dictionaries) ? Is it a good idea to rely on hash code when we're comparing object equality?
Asked
Active
Viewed 138 times
2

fex
- 3,488
- 5
- 30
- 46
-
2Hashtables, and anything that uses them, depend on GetHashCode. That's it, iirc. And the best way to do it is, iirc, to take all int fields, and multiply them with a bunch of primes. – It'sNotALie. Feb 20 '13 at 11:00
-
See also http://blogs.msdn.com/b/ericlippert/archive/2011/02/28/guidelines-and-rules-for-gethashcode.aspx – Jon Skeet Feb 20 '13 at 11:01
-
2You can assume that two equal objects will have the same hash code, but you CANNOT assume that two objects with the same hash code are equal. – Matthew Watson Feb 20 '13 at 11:02
-
So if we can't assume that objects with same hash codes are equal why for instance IEqualityComparer forces us to implement GetHashCode(T) method and not just pure Equals? – fex Feb 20 '13 at 11:08
-
1Because of the first bit: If two objects are considered equal, their hashcodes must be equal. If you implement Equals() without overriding GetHashCode() then Equals() could return true for two objects which have different values for GetHashCode() - which is wrong. (By default GetHashCode() usually returns different values for objects which have different references, even if the fields in those objects are equal.) – Matthew Watson Feb 20 '13 at 13:04
1 Answers
1
I like to use this implementation:
public override int GetHashCode()
{
unchecked
{
int hash = 17;
// Check for null
hash = hash * 29 + field1.GetHashCode();
hash = hash * 29 + field2.GetHashCode();
return hash;
}
}

Community
- 1
- 1

Daniel A.A. Pelsmaeker
- 47,471
- 20
- 111
- 157