Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit <> Explicit interface [duplicate]

Possible Duplicates:
C#: Interfaces - Implicit and Explicit implementation
implicit vs explicit interface implementation

Hello

Can anyone explain me what the difference is between an implicit and explicit interface?

Thanks!

like image 907
Killerwes Avatar asked May 26 '11 13:05

Killerwes


2 Answers

When you implement an interface explicitlty, the methods on that interface will only be visible if the object is referenced as the interface:

public interface IFoo
{
   void Bar();
}

public interface IWhatever
{
   void Method();
}

public class MyClass : IFoo, IWhatever
{
   public void IFoo.Bar() //Explicit implementation
   {

   }

   public void Method() //standard implementation
   {

   }
}

If somewhere in your code you have a reference to this object:

MyClass mc = new MyClass();
mc.Bar(); //will not compile

IFoo mc = new MyClass();
mc.Bar(); //will compile

For the standard implementation, it doesn't matter how you reference the object:

MyClass mc = new MyClass();
mc.Method(); //compiles just fine
like image 80
BFree Avatar answered Sep 24 '22 17:09

BFree


An implicit interface implementation is where you have a method with the same signature of the interface.

An explicit interface implementation is where you explicitly declare which interface the method belongs to.

interface I1
{
    void implicitExample();
}

interface I2
{
    void explicitExample();
}


class C : I1, I2
{
    void implicitExample()
    {
        Console.WriteLine("I1.implicitExample()");
    }


    void I2.explicitExample()
    {
        Console.WriteLine("I2.explicitExample()");
    }
}

MSDN: implicit and explicit interface implementations

like image 26
Yochai Timmer Avatar answered Sep 22 '22 17:09

Yochai Timmer