Wednesday, June 22, 2016

FuncEqualityComparer

Upon implementing a FuncComparer, the very next thing that I do is implement a FuncEqualityComparer; so it follows that I should post this next. An implementation of IEqualityComparer on top of an IComparer is relatively trivial and straightforward,


public class FuncEqualityComparer<T> : 
    FuncComparer<T>, 
    IEqualityComparer, 
    IEqualityComparer<T>
{

    private readonly Func<T, int> getHashCode = null;

    public FuncEqualityComparer(
        Comparison<T> comparison, 
        Func<T, int> getHashCode, 
        bool isNullLessThan = true) :
        this(new[] { comparison, }, getHashCode, isNullLessThan)
    {
    }

    public FuncEqualityComparer(
        Comparison<T>[] comparisons, 
        Func<T, int> getHashCode, 
        bool isNullLessThan = true) :
        base(comparisons, isNullLessThan)
    {
        this.getHashCode = getHashCode;
    }

    // interfaces

    #region IEqualityComparer Members

    public new bool Equals(object x, object y)
    {
        int comparison = Compare(x, y);
        bool isEqual = comparison == 0;
        return isEqual;
    }

    public int GetHashCode(object obj)
    {
        int hashCode = 0;
        T o = default(T);
        if (obj is T)
        {
            o = (T)(obj);
        }
        hashCode = getHashCode(o);
        return hashCode;
    }

    #endregion

    #region IEqualityComparer<T> Members

    public bool Equals(T x, T y)
    {
        int comparison = Compare(x, y);
        bool isEqual = comparison == 0;
        return isEqual;
    }

    public int GetHashCode(T obj)
    {
        int hashCode = getHashCode(obj);
        return hashCode;
    }

    #endregion

}



No real secret sauce here; merely account for GetHashCode and interpret an underlying comparison.