Search code examples
c#tuplesgethashcode

GetHashCode implementation using tuples for derived class


I like to implement GetHashCode using tuples, as described here https://intellitect.com/overidingobjectusingtuple/. However, this doesn't seem to work for a derived class. For example:

class Base
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }

    public override int GetHashCode() => (Prop1, Prop2).GetHashCode();
}

class Derived : Base
{
    public int Prop3 { get; set; }
    public int Prop4 { get; set; }

    public override int GetHashCode() => (Prop3, Prop4, ???).GetHashCode();
}

It's unclear how I'd implement the Derived GetHashCode using a tuple. Any suggestions? We're currently doing it this way, but I'd love to get rid of the unchecked and hash constant:

public override int GetHashCode()
{
    unchecked
    {
        return (base.GetHashCode() * HashCodeConstant) ^ (Prop3, Prop4).GetHashCode();
    }
}

Solution

  • see https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0070

    public override int GetHashCode()
    {
        return System.HashCode.Combine(base.GetHashCode(), Prop3, Prop4);
    }