Sunday, 3 May 2015

Implicit vs. Explicit Interface Implementation

One feature of C# that I find useful is the support of implicitly or explicitly implementing interfaces. For example, if we have a simple interface such as the following:
public interface IDoSomething
{
    void DoIt();
}
You are probably already aware that we can implicitly implement the interface with code like:
public class MyClass : IDoSomething
{
    public void DoIt()
    {
        throw new NotImplementedException();
    }
}
We can use the implementation like:
MyClass myClass = new MyClass();
myClass.DoIt();
If MyClass is to explicitly implement the interface, the MyClass implementation would look like:
public class MyClass : IDoSomething
{
    void IDoSomething.DoIt()
    {
        throw new NotImplementedException();
    }
}
Notice the two differences.
  1. The access modifier has been dropped from the DoIt method signature
  2. The DoIt method name is now qualified with the interface name
So how does this now affect how we use MyClass? Well, you can no longer call the DoIt method on a direct instance of MyClass, you are now forced to code to the interface to access the DoIt method. So our previous code which instantiates MyClass and calls DoIt will no longer compile. Instead you will need to "explicitly" work with an instance of the interface to access the DoIt method. One example would be by declaring the type of the object to be the interface, like the following:
IDoSomething myClass = new MyClass();
myClass.DoIt();
Or you could cast the MyClass instance back to its interface to call the DoIt method, as shown in the following snippet:
MyClass myClass = new MyClass();
((IDoSomething) myClass).DoIt();
So, what are the benefits of explicitly implementing an interface?
  • As the implementer of a class, you can try to force good practice on clients by making them code to an interface
  • As a consequence of the point above, you can reduce tight coupling in your code as it shouldn't be using concrete implementations directly
  • If you are implementing two interfaces which have the same method signatures, or a method signature in an interface clashes with one already visible in your class, you can separate the two methods