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.
void Another()
{
IFoo f = (IFoo)this:
f.Foo();
}
Further reading:
C# Interfaces. Implicit implementation versus Explicit implementation
Try this:
void Another() {
((IFoo)this).Foo();
}
Since you're declaring the Foo method as an explicit interface implementation, you can't reference it on an instance of FooClass. You can only reference it by casting the instance of FooClass to IFoo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With