Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 870
RickySpanish Avatar asked Oct 27 '16 09:10

RickySpanish


1 Answers

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.

like image 175
BoltClock Avatar answered Oct 05 '22 02:10

BoltClock