How to use System.HashCode.Combine with more than 8 values?

As stated in the System.HashCode documentation, adding together hashes returned by successive HashCode.Combine calls is NOT the solution.

While the static HashCode.Combine method overloads only allow up to 8 values, these are just convenience methods – to combine more, instantiate the HashCode class itself and use it as follows:

public override int GetHashCode()
{
    HashCode hash = new();
    hash.Add(M11);
    hash.Add(M12);
    hash.Add(M13);
    hash.Add(M21);
    hash.Add(M22);
    hash.Add(M23);
    hash.Add(M31);
    hash.Add(M32);
    hash.Add(M33);
    return hash.ToHashCode();
}

It does make me wonder why there is no HashCode constructor accepting a params object[] values so you could do all that in one line, but there are probably reasons I didn’t think of this quickly. (S. the comments why such an overload does not exist.)

Leave a Comment

tech