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.
- public interface IMan {
- void Eat();
- }
- public interface IBirds {
- void Eat();
- }
- public class MyClass: IMan, IBirds {
- void IMan.Eat() {
- Console.WriteLine("Roti");
- }
- void IBirds.Eat() {
- Console.WriteLine("Earthworms");
- }
- }
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.
- IMan man = new MyClass();
- man.Eat();
- IBirds birds = new MyClass();
- birds.Eat();
-
- ((IMan) new MyClass()).Eat();
- ((IBirds) new MyClass()).Eat();