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:

    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.

IMan man = new MyClass();
man.Eat();
IBirds birds = new MyClass();
birds.Eat();

//OR

((IMan)new MyClass()).Eat();
((IBirds)new MyClass()).Eat();

Leave a Reply

Your email address will not be published. Required fields are marked *