Why does the following not compile?
interface IFoo
{
void Foo();
}
class FooClass : IFoo
{
void IFoo.Foo() { return; }
void Another() {
Foo(); // ERROR
}
}
The compiler complains that “The name ‘FooMethod’ does not exist in the current context”.
However, if the Foo method is changed to:
public void Foo() { return; }
this compiles just fine.
I don’t understand why one works and the other does not.
Because when you “explicitly implement” an interface, you can only access the method by casting to the interface type. Implicit casting will not find the method.
Further reading:
C# Interfaces. Implicit implementation versus Explicit implementation