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

1

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?

Hasid answered 27/10, 2016 at 9:55 Comment(2)
No, it doesn't. You just need to make the method in the first version public in order to implement the interface.Broomstick
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.Bonilla
I
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.

Irascible answered 27/10, 2016 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.