Explicit Interface Implementation in C#

Explicit Interface Implementation

  1. Simple explanation of how to explicitly implement interface and how to access those interface members from the interface instances.

  2. A class can explicitly implement the interface members.

  3. By this ways of implementing the explicit interface, we can have a class implementing multiple interface with same member definition.

  4. Now let’s see in following code how to explicitly implement interface members and also how to differentiate interface members having same member definition across multiple interface.

Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace Explicit_interface  
  6. {  
  7.     interface capswriter  
  8.     {  
  9.         string writename();  
  10.     }  
  11.     interface  smallwriter  
  12.     {  
  13.         string writename();  
  14.     }  
  15.     class caption : capswriter, smallwriter  
  16.     {  
  17.         string firstname;  
  18.         public caption(string N)  
  19.         {  
  20.             this.firstname = N;  
  21.         }  
  22.          string capswriter.writename()  
  23.         {  
  24.             return this.firstname.ToUpper();  
  25.         }  
  26.          string smallwriter.writename()  
  27.         {  
  28.             return this.firstname.ToLower();  
  29.         }  
  30.     }  
  31.     class Program  
  32.     {  
  33.         static void Main(string[] args)  
  34.         {  
  35.             caption obj = new caption("Harish Sady");  
  36.             capswriter obj_caps = (capswriter)obj;  
  37.             smallwriter obj_small = (smallwriter)obj;  
  38.             Console.WriteLine("-- Output of capswriter Interface---");  
  39.             Console.WriteLine(obj_caps.writename());  
  40.             Console.WriteLine("-- Output of smallwriter Interface---");  
  41.             Console.WriteLine(obj_small.writename());  
  42.             Console.ReadKey();  
  43.         }  
  44.     }  
  45. }  
Explanation
  1. caption obj = new caption("Harish Sady");  

  1. Since we have mention the interface members explicitly, we cannot access those interface members using class objects.

    interface

  2. To access those members, we should cast the class object to respective interface.
    1. capswriter obj_caps = (capswriter)obj;  
  3. So class objects is casted to “capswriter” interface.

  4. Now we can access the “writename” method by the interface instance.

    writename

Output

Output

Ebook Download
View all
FileInfo in C#
Read by 9.7k people
Download Now!
Learn
View all