Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a method prefixed with the interface name not compile in C#?

Tags:

c#

interface

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.

like image 619
tgiphil Avatar asked Jul 27 '10 20:07

tgiphil


2 Answers

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

like image 170
Adam Houldsworth Avatar answered Sep 20 '22 02:09

Adam Houldsworth


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.

like image 25
John Bledsoe Avatar answered Sep 22 '22 02:09

John Bledsoe