Below is a sample implementation of overriding Object.Equals() for an entity base class from which all other entities in an application derive.
All entity classes have the property Id, which is a nullable int. (It’s the primary key of whatever table the entity class corresponds to.)
public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; if (base.Equals(obj)) return true; return Id.HasValue && ((EntityBase) obj).Id.HasValue && Id.Value == ((EntityBase) obj).Id.Value; }
Given this implementation of Equals(), how do you correctly implement GetHashCode()?
If you’re deriving from something that already overrides
GetHashCodeI’d implement it as:A null value of Id will return 0 for Id.GetHashCode().
If your class just derives from Object, I’d just return
Id.GetHashCode()– you do not want to include theobject.GetHashCodeimplementation in your hash code, as that basically ends up being object identity.Note that your equality definition won’t return
trueif neither entity has an Id, but the same hashcode will be returned from both objects. You may wish to consider changing your Equals implementation.