Sunday, March 8, 2015

Implicit vs Explicit interface implementations in C#

It's a very small but very important concept to be learnt. It's very normal to use the interfaces in our applications. But at the same time, it's very important to make sure that these interfaces are implemented correctly. So whenever we implement an interface in C#, we get two different to implement it i.e. either Implicitly or Explicitly:

But what's the difference between the two. To understand it in better way, let's first create two classes and implement an interface implicitly for ClassA and explicitly for ClassB.

Now let's create another class ClassC and try to access the GetData method of both these classes i.e. ClassA and ClassB. Can we access that method for both ? See the code below:

We can do it for ClassA but not for ClassB. This is the main difference between the two implementations. For any explicitly implemented interface, you cannot access the interface methods until you create the instance of the class to be of particular interface type. Now let's instantiate the ClassB instance as ISampleInterface type and try to access the method.

This time it's accessible. Now the question is when to use explicit interface implementation. Following are some of the points that can help us to decide which to use when.
1.  Suppose you have a DLL of some API for your clients. This includes a class which implements two interfaces ISampleA and ISampleB. ISampleA is using the methods of ISampleB for some functionality, however the client has no concern with ISampleB methods as he is using ISampleA. Now is this wise enough to expose the methods of ISampleB through the use of the implicit interface implementation. So the idea should be to use implicit implementation for ISampleA and explicit implementation for ISampleB.
But of-course, if the client get's to know about ISampleB interface, he can create the instance of the class to be of type ISampleB and access its methods.
2. Another scenario, both your interfaces have a common method GetData() or even your class has a method named GetData(). Implicit implementation of interfaces will not allow you to do this. You will error something like the one below:
The call is ambiguous between the following methods or properties: 'InterfaceImplementations.ClassA.GetData()' and 'InterfaceImplementations.ClassA.GetData()' 
So these are two cases which I think help you decide whether to use implicit or explicit interface implementation.If you have any other than do share with us. Happy coding...!!!

No comments:

Post a Comment