Thursday 18 May 2017

C# – How to implement two interfaces having same method names in a class






We have two interfaces IMan and IBirds. Both the interfaces defines a method named Eat with 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 is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 object of the derived class to it.
1
2
3
4
5
6
7
8
9
IMan man = new MyClass();
man.Eat();
IBirds birds = new MyClass();
birds.Eat();
//OR
((IMan)new MyClass()).Eat();
((IBirds)new MyClass()).Eat();