Good GetHashCode() override for List of Foo objects respecting the order

I’d do it the same way I normally combine hash codes – with an addition and a multiplication:

public override int GetHashCode()
{
    unchecked
    {
        int hash = 19;
        foreach (var foo in foos)
        {
            hash = hash * 31 + foo.GetHashCode();
        }
        return hash;
    }
}

(Note that you shouldn’t add anything to the list after this has been used for the key in a hash table of any description, as the hash will change. This also assumes that there are no null entries – if there could be, you need to take account of that.)

Leave a Comment