Search code examples
c#.net-coregethashcode

When overriding GetHashCode() should you also factor in the base class's HashCode?


class A
{
    public int Age{get;set;}
    public override GetHashCode()
    {
        return Age.GetHashCode();
    }
}

class B : A
{
    public int Name{get;set;}
    public override GetHashCode()
    {
        return HashCode.Combine(base.GetHashCode(), Name);
    }
}

Is the GetHashCode method in type B how to properly override GetHashCode, or would you just calculate the hash code of the fields in type B only?


Solution

  • The purpose of GetHashCode() is to enable different algorithms to quickly determine if two objects of your class are definitely not equal, before they have to consult a maybe inefficient Equals method, and to allow data structures like HashSet or Dictionary to sort objects into buckets.

    The only requirement for GetHashCode is that two objects that compare equal (by the Equals method) must produce the same hash code (on the other hand, it is OK if two objects producing the same hash code are not equal).

    It is best to construct the hash code so that

    • collsions are rare
    • but still the implementation is performant.

    What is the best way to do this, depends on the nature and usage of your class and only you can decide.

    BTW: It is (in general) a bad idea to include mutable properties in the hash, as this makes it impossible to use your class e.g. as key in a dictionary.