Josh Kodroff Josh Kodroff - 2 months ago 12x
C# Question

What is the correct implementation for GetHashCode() for entity classes?

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 GetHashCode I'd implement it as:

public override int GetHashCode()
        int hash = 37;
        hash = hash * 23 + base.GetHashCode();
        hash = hash * 23 + Id.GetHashCode();
        return hash;

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 the object.GetHashCode implementation in your hash code, as that basically ends up being object identity.

Note that your equality definition won't return true if neither entity has an Id, but the same hashcode will be returned from both objects. You may wish to consider changing your Equals implementation.