Reputation:
I don't quite understand how explicit implementation works, so I made a mockup
public class ShoppingCart : IEnumerable<Product>
{
public IEnumerator<Product> GetEnumerator()
{
return Products.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() //why 'public' is not needed?
{
return GetEnumerator(); // why there is not any error here?
}
}
Below is my mockup:
class MockUp: Ilayer1
{
public string testMethod()
{
return "Layer1";
}
string Ilayer2.testMethod() // error, not all code path return a value
{
testMethod();
}
}
interface Ilayer1 : Ilayer2
{
string testMethod();
}
interface Ilayer2
{
string testMethod();
}
but I have a compilation error, but why there is no error for ShoppingCart?
And how can I make my MockUp class work?
Upvotes: 0
Views: 57
Reputation: 186668
Let me answer the questions one after one:
why 'public' is not needed?
Since if we put public
we'll have an ambiguity:
public IEnumerator<Product> GetEnumerator() {...}
public IEnumerator IEnumerable.GetEnumerator() {...}
And in case of ShoppingCart.GetEnumerator();
which method will be executed? That's why explicit interface implementation is effectively private
// public
public IEnumerator<Product> GetEnumerator() {...}
// private
IEnumerator IEnumerable.GetEnumerator() {...}
So far so good in case of ShoppingCart.GetEnumerator();
we call the only public
method (with no ambiguity). In case of (ShoppingCart as IEnumerable).GetEnumerator();
we call an interface implementation whatever it is (again we have only one method which fits).
I have a compilation error, but why there is no error for ShoppingCart?
string Ilayer2.testMethod() // error, not all code path return a value
{
testMethod();
}
The method should return string
, but it doesn't do it. Add return
:
string Ilayer2.testMethod() // error, not all code path return a value
{
return testMethod();
}
Or even
string Ilayer2.testMethod() => testMethod();
Upvotes: 0