Search code examples
c#gethashcode

Generic IEqualityComparer<T> and GetHashCode


Being somewhat lazy about implementing lots of IEqualityComparers, and given that I couldn't easily edit class implementations of the objects being compared, I went with the following, meant to be used with Distinct() and Except() extension methods:

public class GenericEqualityComparer<T> : IEqualityComparer<T>
{
    Func<T, T, bool> compareFunction;
    Func<T, int> hashFunction;

    public GenericEqualityComparer(Func<T, T, bool> compareFunction, Func<T, int> hashFunction)
    {
        this.compareFunction = compareFunction;
        this.hashFunction = hashFunction;
    }

    public bool Equals(T x, T y)
    {
        return compareFunction(x, y);
    }

    public int GetHashCode(T obj)
    {
        return hashFunction(obj);
    }
}

This seems nice, but is giving a hash function every time REALLY necessary?

I understand that the hash code is used to put objects in buckets. If in different buckets, objects are not equal, and Equal is not called.

If GetHashCode returns the same value, Equals is called. (From: Why is it important to override GetHashCode when Equals method is overridden?)

So what could go wrong, if for example (and I hear a lot of programmers screaming in horror), GetHashCode returns a constant, to force the call to Equal?


Solution

  • Nothing would go wrong, but in hash-table based containers, you're going from approx O(1) to O(n) performance when doing a lookup. You'd be better off simply storing everything in a List and brute force searching it for items that fulfil equality.