Thursday, 12 March 2015

Implicit vs Explicit Interface Implementations


Introduction
It's a very small but very important concept to be learned. It's very normal to use the interfaces in our applications. But at the same time, it's very important to ensure that these interfaces are implemented correctly. So whenever we implement an interface in C#, we get two ways to implement it, in other words either implicitly or explicitly.



But what's the difference between the two? To understand it better, 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, in other words 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 a specific interface type. Now let's instantiate the ClassB instance as an ISampleInterface type and try to access the method.



This time it's accessible. Now the question is, when to use the explicit interface implementation. The following are some of the points that can help us to decide which to use and when.
  1. Suppose you have a DLL of some API for your clients. This includes a class that implements the two interfaces, ISampleA and ISampleB. ISampleA uses the methods of ISampleB for some functionality, however the client has no concern with ISampleB methods since he is using ISampleA. Now is this good enough to expose the methods of ISampleB using the implicit interface implementation? So the idea should be to use an implicit implementation for ISampleA and an explicit implementation for ISampleB.

    Of course, if the client becomes familiar with the ISampleB interface then he can create the instance of the class to be of type ISampleB and access its methods.
  2. Another scenario is for both your interfaces to have a common method, GetData(), or even your class has a method named GetData(). An implicit implementation of interfaces will not allow you to do this. You will get an error, something like the one below:

The call is ambiguous between the following methods or properties: 'InterfaceImplementations.ClassA.GetData()' and 'InterfaceImplementations.ClassA.GetData()' 

Use the explicit implementations and you can use multiple methods with the same name.

So these are two cases that I think will help you decide whether to use implicit or explicit interface implementation.If you have any other then do share with us. Happy coding!

No comments:

Post a Comment