Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, why do interface implementations have to implement a another version of a method explicitly?

Take this example:

public interface IFoo
{
    IFoo Bar();
}

public class Foo : IFoo
{
    public Foo Bar()
    {
        //...
    }

    IFoo IFoo.Bar() { return Bar(); } //Why is this necessary?
}

Why is the implicit implementation of IFoo Bar() necessary even though Foo converts to IFoo without a cast?

like image 707
Matt Avatar asked Dec 19 '12 19:12

Matt


1 Answers

It's needed in this case because C# does not support return type co-variance for interfaces, so your function

public Foo Bar()
{
    //...
}

does not satisfy the IFoo interface since the return type of the Bar method is different.

Since you want to also implement the interface, your only choice is to do so explicitly since you already have a Bar() method defined on the class.

like image 151
Lee Avatar answered Oct 11 '22 22:10

Lee