Reputation: 3512
Hi I have a class with 6 string properties. A unique object will have different values for atleast one of these fields
To implement IEqualityComparer's GetHashCode function, I am concatenating all 6 properties and calling the GetHashCode on the resultant string.
I had the following doubts:
Upvotes: 10
Views: 1140
Reputation: 5113
You can use the behavior from:
http://moh-abed.com/2011/07/13/entities-and-value-objects/
Upvotes: 0
Reputation: 2625
If your string fields are named a-f and known not to be null, this is ReSharper's proposal for your GetHashCode()
public override int GetHashCode() {
unchecked {
int result=a.GetHashCode();
result=(result*397)^b.GetHashCode();
result=(result*397)^c.GetHashCode();
result=(result*397)^d.GetHashCode();
result=(result*397)^e.GetHashCode();
result=(result*397)^f.GetHashCode();
return result;
}
}
Upvotes: 4
Reputation: 437326
GetHashCode
does not need to return unequal values for "unequal" objects. It only needs to return equal values for equal objects (it also must return the same value for the lifetime of the object).
This means that:
Equals
, then their GetHashCode
must return the same value.GetHashCode
implementation.If you cannot satisfy both points at the same time, you should re-evaluate your design because anything else will leave the door open for bugs.
Finally, you could probably make GetHashCode
faster by calling GetHashCode
on each of the 6 strings and then integrating all 6 results in one value using some bitwise operations.
Upvotes: 3
Reputation: 11101
GetHashCode() should return the same hash code for all objects that return true if you call Equals() on those objects. This means, for example, that you can return zero as the hash code regardless of what the field values are. But that would make your object very inefficient when stored in data structures such as hash tables.
Combining the strings is one option, but note that you could for example combine just two of the stringsfor the hash code (while still comparing all the strings in equals!).
You can also combine the hashes of the six separate strings, rather than computing a single hash for a combined string. See for example Quick and Simple Hash Code Combinations
I'm not sure if this will be significantly faster than concatenating the string.
Upvotes: 3