Explicit Interface Implementation
- Simple explanation of how to explicitly implement interface and how to access those interface members from the interface instances.
- A class can explicitly implement the interface members.
- By this ways of implementing the explicit interface, we can have a class implementing multiple interface with same member definition.
- 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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Explicit_interface
- {
- interface capswriter
- {
- string writename();
- }
- interface smallwriter
- {
- string writename();
- }
- class caption : capswriter, smallwriter
- {
- string firstname;
- public caption(string N)
- {
- this.firstname = N;
- }
- string capswriter.writename()
- {
- return this.firstname.ToUpper();
- }
- string smallwriter.writename()
- {
- return this.firstname.ToLower();
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- caption obj = new caption("Harish Sady");
- capswriter obj_caps = (capswriter)obj;
- smallwriter obj_small = (smallwriter)obj;
- Console.WriteLine("-- Output of capswriter Interface---");
- Console.WriteLine(obj_caps.writename());
- Console.WriteLine("-- Output of smallwriter Interface---");
- Console.WriteLine(obj_small.writename());
- Console.ReadKey();
- }
- }
- }
Explanation
- caption obj = new caption("Harish Sady");
- Since we have mention the interface members explicitly, we cannot access those interface members using class objects.
- To access those members, we should cast the class object to respective interface.
- capswriter obj_caps = (capswriter)obj;
- So class objects is casted to “capswriter” interface.
- Now we can access the “writename” method by the interface instance.
Output