Search code examples
c#hashcode

What is the best way to implement GetHashCode() for class with lots of properties?


I have a class that has lots of properties that I am implementing IEquitable<T> on. I have found multiple examples on how to do GetHashCode() for small amount of properties.

Here is one example

public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        // Suitable nullity checks etc, of course :)
        hash = hash * 23 + field1.GetHashCode();
        hash = hash * 23 + field2.GetHashCode();
        hash = hash * 23 + field3.GetHashCode();
        return hash;
    }
}

How should I go around when I have hundreds of properties on object?


Solution

  • Old questions sometimes have new better answers HashCode.Combine:

    public override int GetHashCode()
    {
        return HashCode.Combine(field1, field2, field3);
    }