'Why is GetHashCode not called during Contains?

Until today my understanding was that a HashSet uses GetHashCode inside Contains. That is also said e.g. here.

I wrote a little IEqualityComparer:

public class MyComparer : IEqualityComparer<string>
{
    public bool Equals(string? a, string? b)
    {
        return a == b;
    }

    public int GetHashCode(string a)
    {
        throw new NotImplementedException();
    }
}

And used it like so:

public void TestMyComparer()
{
    var x = new HashSet<string>(new []{ "hello", "world" });
    bool helloInside = x.Contains("hello", new MyComparer());
}

But TestMyComparer does not throw a NotImplementedException, as I expected. Instead, it returns true.

Why?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source