Search code examples
c#abstract-classiequalitycomparer

IEqualityComparer error


I'm following a tutorial from C# 7.0 in a Nutshell and getting an error that I can't fix. The way that I understood the error is that the method needs to be an abstract method, which I also tried, but that didn't resolve the error. And I thought abstract classes allowed non-abstract methods in them.

Here is the code:

public abstract class EqualityComparer<T>: IEqualityComparer, IEqualityComparer<T>
{
    public abstract bool Equals(T x, T y);
    public abstract int GetHashCode(T obj);

    bool IEqualityComparer.Equals(object x, object y);
    int IEqualityComparer.GetHashCode(object obj);

    public static EqualityComparer<T> Default { get; }
}

Here is the error:

'EqualityComparer<T>.IEqualityComparer.Equals(object, object)' must declare a body because it is not marked abstract, extern, or partial

Please let me know what I'm doing wrong.


Solution

  • Yous have to implement the methods (explicit interface implementation makes the methods efficiently private which prevent them from being abstract: you can't declare, say, abstract bool IEqualityComparer.Equals... ), e.g.:

    bool IEqualityComparer.Equals(object x, object y) {
      if (x is T && y is T)
        return this.Equals((T)x, (T)y); // known types, run Equals
      else
        return object.Equals(x, y);     // unknown type(s), run default Equals 
    }
    
    int IEqualityComparer.GetHashCode(object obj) {
      if (obj is T)
        return this.GetHashCode((T)obj);
      else
        return null == obj ? 0 : obj.GetHashCode();
    }