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!
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!
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
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()");
}
}
Explicit simply means that you specify the interface, implicit means that you don't.
For example:
interface A
{
void A();
}
interface B
{
void A();
}
class Imp : A
{
public void A() // Implicit interface implementation
{
}
}
class Imp2 : A, B
{
public void A.A() // Explicit interface implementation
{
}
public void B.A() // Explicit interface implementation
{
}
}
Also, if you want to know why explicit implementation exists, that's because you may implement the same method (name and signature) from more than one interface; then if you need different functionality, or just the return types are different, you can't achieve this through simple overloading. then you'll have to use explicit implementation. One example is that List<T>
implements IEnumerable
and IEnumerable<T>
and both have GetEnumerator()
but with different return values.