Overriding GetHashCode
is required when you override Equals
, otherwise hash-based containers might not work correctly. From the documentation of Object.Equals
:
Types that override Equals must also override GetHashCode; otherwise, Hashtable might not work correctly.
Even though the code may not get exercised in your case, you should keep it anyway. In addition to being correct, it would help you test equality of collections regardless of their sequence:
Assert.IsTrue(expected.Except(actual).Count() == 0);
One change I would make to the GetHashCode
implementation is eliminating its symmetry: currently, switching around the first and the last name inside your object would lead to making the same hash code. This is sub-optimal. You can combine multiple int
s int a hash code by multiplying them by a small prime number, e.g. 31, and adding them up, like this:
public override int GetHashCode()
{
int hashClaimId = this.ClaimId == null ? 0 : this.ClaimId.GetHashCode();
int hashFirstname = this.Firstname == null ? 0 : this.Firstname.GetHashCode();
int hashLastname = this.Lastname == null ? 0 : this.Lastname.GetHashCode();
return 31*31*hashClaimId + 31*hashFirstname ^ hashLastname;
}