Implicit and Explicit Interface Implementation in C#

An interface in C# is usually used to create loosely-coupled and contract-based designs. It can contain signatures (declarations) of the Methods, Properties, Indexers and Events. The implementation of the methods/properties and so on is done in the class that implements the interface. An interface can inherit one or more interfaces, in other words it supports multiple inheritance whereas classes don't.

Implicit interface implementation

This is the most regular or obvious way  to implement members of an interface. Here we don't specify the interface name of the members and implement implicitly. The method can be declared at any interface (s) the class implements.
 
For example:
  1. interface ITest   
  2. {  
  3.     void TestMethod();  
  4. }  
  5. class TestClass: ITest  
  6. {  
  7.     public void TestMethod()  
  8.     {  
  9.         Console.WriteLine("Implicit Interface Implementation");  
  10.     }  
  11. }   
The call of the method is also not different. Just create an object of the class and invoke it.
  1. class Program   
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         TestClass obj = new TestClass();  
  6.         obj.TestMethod(); //Way to call implicitely implemented method  
  7.     }  
  8.   
  9. }  
Output

 
 
Explicit interface implementation

This is another way to implement members of an interface. Here we need to specify the interface name of the members. The following example explains that.
  1. class TestClass: ITest   
  2. {  
  3.     void ITest.TestMethod()  
  4.     {  
  5.         Console.WriteLine("Explicit Interface Implementation");  
  6.     }  
  7. }  
The constraint with explicit implementation is that an explicitly implemented member cannot be accessed using a class instance, but only through an instance of the interface. Please have a look at the example below.
  1. class Program   
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.     ITest obj2 = new TestClass();  
  6.         obj2.TestMethod();  
  7.     }  
  8. }  
 Output

 
 
I hope you have liked the article. Please share your comments.