8

I'm fairly new to C# (6 months on the job experience), but it seems pretty similar to Java so I feel right at home.

However, today I tried implementing the IComparer interface and wondered why it was giving me an error:

public class AlphabeticalReportSort : IComparer
{
    int Compare(Object x, Object y)
    {
        return 0;
    }
}

It seems like it requires you to implement it as:

public class AlphabeticalReportSort : IComparer
{
    int IComparer.Compare(Object x, Object y)
    {
        return 0;
    }
}

I didn't notice anything in the interface declaration that would require this, and it seems like in C# you don't normally need to do this.

Anybody know why?

RickySpanish
  • 501
  • 1
  • 3
  • 10
  • 2
    No, it doesn't. You just need to make the method in the first version public in order to implement the interface. – Jon Skeet Oct 27 '16 at 09:59
  • Of course, Jon Skeet is right. The methods have to be implemented *public* because they have to be callable through the interface, thus from where the interface is accessible as a type. For detailed explanation check [that link](http://stackoverflow.com/questions/7238575/why-must-an-c-sharp-interface-method-implemented-in-a-class-be-public). – Farhad Jabiyev Oct 27 '16 at 10:03

1 Answers1

9

Why does IComparer require you to define IComparer.Compare(Object x, Object y) and not just Compare(Object x, Object y)?

It doesn't. The full error message is:

'AlphabeticalReportSort' does not implement interface member 'IComparer.Compare(object, object)'. 'AlphabeticalReportSort.Compare(object, object)' cannot implement an interface member because it is not public.

Note the second sentence. Your int Compare() method is private, not public, and therefore cannot act as an implementation of the interface method.

int IComparer.Compare() is an explicit implementation, and it compiles because explicit interface implementations are always public (as all interface members are public) and therefore do not require the access modifier. But in your case, simply marking your method public is sufficient. Very rarely are you required to implement an interface method explicitly, and as far as I know you can't actually require this in the interface definition itself.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356