EagerToLearn
EagerToLearn

Reputation: 857

Same name in 2 methods in 2 different interfaces, why not 1 implementation?

If I have 2 methods with the same name, but with different return types. They are inherited by a class from 2 interfaces. This class can provide 1 implementation for both if the return type for implementation conforms to return type in both interfaces.

For example, String type implements both methods: IEnumerable and IEnumerable<char>. The implementation for String type contains just one implementation for GetEnumerator.

public CharEnumerator GetEnumerator();

I believe this is possible because CharEnumerator implements both IEnumerator and IEnumerator<char>

public CharEnumerator: IEnumerator, IEnumerator<char>

However, a similar code in my application below gives me a compilation error,

interface Ia { IEnumerator o();}
interface Ib { IEnumerator<int> o();}
class e : IEnumerator, IEnumerator<int>{}
class c : Ia, Ib { public e o() { return new e(); } }

If I do a F12 on String type in Visual Studio, I see something like below, enter image description here

As you can see, there is only 1 implicit implementation of GetEnumerator(), no explicit implementations there

Upvotes: 1

Views: 72

Answers (1)

InBetween
InBetween

Reputation: 32780

String does not implicitly implement IEnumerable or IEnumerable<char>. It does so explicitly, which means you can only access the methods through an IEnumerable or IEnumerable<char> reference.

The method CharEnumerator GetEnumerator() implements neither interface because the return type is not a IEnumerator or a IEnumerator<T>; CharEnumerator is one possible IEnumerator but the interface is asking for any IEnumerator.

Explicit interfaces are very useful, you have just stumbled on one of the features they provide; implementing in one class different interfaces that define a method with the same name:

interface IFoo
{
    IFoo Frob();
}

interface IBar
{
    IBar Frob();
}

public class Blah: IFoo, IBar
{
    Foo IFoo.Frob() => new Foo();
    Bar IBar.Frob() => new Bar();
    void Frob();
}

And now, you'll get the following behavior:

var b = new Blah();
b.Frob(); //returns nothing, this method is not implementing any of the two interfaces.
(b as IBar).Frob(); //returns a bar
(b as IFoo).Frob(); //returns a foo

Upvotes: 2

Related Questions