How To Implement Two Interfaces Having Same Method Names In A Class

We have two interfaces IMan and IBirds. Both the interfaces define a method named Eat with the same name and signature. A class MyClass is inheriting both the interfaces. How can we implement method of both the interfaces in the derived class MyClass?

Here, the code is given below. 

  1. public interface IMan {  
  2.     void Eat();  
  3. }  
  4. public interface IBirds {  
  5.     void Eat();  
  6. }  
  7. public class MyClass: IMan, IBirds {  
  8.     void IMan.Eat() {  
  9.         Console.WriteLine("Roti");  
  10.     }  
  11.     void IBirds.Eat() {  
  12.         Console.WriteLine("Earthworms");  
  13.     }  
  14. }  

We use interface name to access its method to implement.

Similarly, we call a method by instantiating the desired interface and assigning an object of the derived class to it.

  1. IMan man = new MyClass();  
  2. man.Eat();  
  3. IBirds birds = new MyClass();  
  4. birds.Eat();  
  5. //OR  
  6. ((IMan) new MyClass()).Eat();  
  7. ((IBirds) new MyClass()).Eat();  

Ebook Download
View all
Learn
View all