Thursday, December 23, 2010

What is Explicit and Implicit Interface Implementation

Yes, very much. Did you know other than the syntax difference between the two, there existed a fundamental difference.

Implicit interface implementation on a class would be a public method by default and is accessible on the class's object or the interface.

Explicit interface implementation on a class would be a private method by default and is only accessible through the interface and not through the class object unlike the implicit implementation. Yes, through this you can force you clients to use the Interface and not the objects that implement it.

public interface IMyInterface
{
void MyMethod(string myString);
}
CLASS THAT IMPLEMENTS THE INTERFACE IMPLICITLY
public MyImplicitClass: IMyInterface
{
public void MyMethod(string myString)
{
///
}
}
CLASS THAT IMPLEMENTS THE INTERFACE EXPLICITLY
public MyExplicitClass: IMyInterface
{
void IMyInterface.MyMethod(string myString)
{
///
}
}
MyImplicitClass instance would work with either the class or the Interface:
MyImplicitClass myObject = new MyImplicitClass();
myObject.MyMethod("");
IMyInterface myObject = new MyImplicitClass();
myObject.MyMethod("");
MyExplicitClass would work only with the interface:
//The following line would not work.
MyExplicitClass myObject = new MyExplicitClass();
myObject.MyMethod("");
//This will work
IMyInterface myObject = new MyExplicitClass();
myObject.MyMethod("");

No comments: