Question

Is there a built-in IEqualityComparer that compares objects by the value returned by their GetHashCode value? It's easy to write, but I'd prefer to use a provided class instead of a custom one.

Current code:

private class HashComparer : IEqualityComparer<TKey>
{
    private readonly Func<TKey, int> _Hasher;

    public HashComparer (Func<TKey, int> hasher)
    {
        _Hasher = hasher;
    }

    public bool Equals (TKey x, TKey y)
    {
        // null supposed to throw, therefore no check
        return _Hasher (x) == _Hasher (y);
    }

    public int GetHashCode (TKey obj)
    {
        return _Hasher (obj);
    }
}
Was it helpful?

Solution

No, such a thing doesn't exist in the framework as far as I'm aware.

It would be a generally Bad Thing - hash codes don't have to be unique, so it couldn't be used to mimic normal equality, other than for types with 2^32 possible values or fewer, and a hash generation algorithm which gives a unique code for each value.

I'm struggling to think of any sensible use for this - which is why you're unlikely to find it in the framework. Perhaps there's some very specialized situation where you'd find it useful, but that's not enough justification to put it in the main framework.

Out of interest, what are you trying to do with it?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top