Normally an interface can be implemented in a class in a normal way, implicit implementation. Sometimes, we may have the same method name in different interfaces. If this is the case, we need to do an explicit implementation of the interface method. The main use of an explicit implementation is to avoid the ambiguities between the class or method name. In order to do that the interface name is put before that interface's method. The following example shows the implicit and explicit implementation:
- namespace ConsoleApplicationC
- {
-
- interface IintegerAdd
- {
- void Add();
- }
- interface IfloatAdd
- {
- void Add();
- void Multiply();
- }
-
-
- class ArithmeticOperation : IintegerAdd, IfloatAdd
- {
-
-
- public void Multiply()
- {
- float a = 1.5f, b = 2.5f;
- Console.WriteLine("Float Multiplication is:" + a * b);
- }
-
-
- void IintegerAdd.Add()
- {
- int a = 10, b = 20;
- Console.WriteLine("Integer Addition Is:" + (a + b));
- }
-
-
- void IfloatAdd.Add()
- {
- float a = 1.5f, b = 2.5f;
- Console.WriteLine("Float Addition Is:" + (a + b));
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- ArithmeticOperation objA = new ArithmeticOperation();
- IintegerAdd iobj = (IintegerAdd)objA;
- iobj.Add();
- IfloatAdd fobj = (IfloatAdd)objA;
- fobj.Add();
- Console.ReadKey();
- }
- }
- }
Output:
Integer Addition Is:30
Float Addition Is:4
The purpose of "Explicit" implementation of an Interface
There are 2 purposes of explicit implementation of an interface. First, to avoid name collision between interface methods. That is, if you are going to create a class library, there may be a chance to use the same name in several places. At that time "explicit" implementation comes to the rescue. Secondly, you cannot access that implemented method using the object of the class directly. Instead you typecast it as an interface reference, then you can access it. This is because the C# compiler is unable to determine which one the user wants to call.
In another way, you need to add a "public" access specifier to the interface's implemented method in a class. But if you "explicitly" implement the interface then you can change this one. That means, it will look like a private method. But with one exception, you can access that explicit implemented method using the reference of the interface. Please have a look at the following code for a detailed explanation.
- interface ISample
- {
- void method1();
- void method2();
- }
- interface IAnotherSample
- {
- void method1();
- }
- class A : ISample, IAnotherSample
- {
-
- void ISample.method1()
- {
-
- }
- void IAnotherSample.method1()
- {
- }
-
- public void method2()
- {
-
- }
-
- }
-
- class B : A
- {
-
- A obj = new A();
- B()
- {
-
- obj.method2();
-
-
-
- ((ISample)obj).method1();
- }
- }
Finally, one more point or little pros is that an explicitly implemented interface's methods are not listed in the Visual Studio IDE's intellisense.
Happy Coding!