How To Inherit Multiple Interfaces Having Same Method Name

In this article, we will see how more than one interface inherits one class with the same method name and learn how to call a particular interface method when more than one interface inherits one class with the same method name.

First, we need to know what is interface?

Like class, the interface has its own members like methods, properties, indexers, and events. But interface will contain only the declaration of the members.

In C#, an interface can be defined using the interface keyword.

Example: C# Interface

interface Mango {
    void PrintName();
}

Now Creating two Interface with the Same Method Name

Now we create interfaces named Mango and Apple. The Mango and Apple interfaces contain functions with the same name, PrintName().

interface Mango {
    void PrintName();
}
interface Apple {
    void PrintName();
}

Now we will see how to implement interface Mango and Apple methods in Fruit class.

using System;
namespace InterfaceExample {
    interface Mango {
        void PrintName();
    }
    interface Apple {
        void PrintName();
    }
    class Fruit: Mango, Apple {
        public void PrintName() {
            Console.WriteLine("Call 'PrintName' method. Mango or Apple??");
        }
    }
    class Program {
        static void Main(string[] args) {
            Fruit fruit = new Fruit();
            fruit.PrintName();
            Console.ReadLine();
        }
    }
}

Output

You can see the above output. It's confusion about which method of which interface is implemented.

For this situation, we need to tell the compiler which interface method we want to implement. we have to add an interface name during the implementation of a method.

You can follow below example,

using System;
namespace InterfaceExample {
    interface Mango {
        void PrintName();
    }
    interface Apple {
        void PrintName();
    }
    class Fruit: Mango, Apple {
        void Mango.PrintName() {
            Console.WriteLine("Call 'PrintName' Method of Mango Interface.");
        }
        void Apple.PrintName() {
            Console.WriteLine("Call 'PrintName' Method of Apple Interface.");
        }
    }
    class Program {
        static void Main(string[] args) {
            Mango mango = new Fruit();
            mango.PrintName();
            Apple apple = new Fruit();
            apple.PrintName();
            Console.ReadLine();
        }
    }
}

Output

You can see in the above example we need to override two methods one for the Mango interface and one for the Apple interface. if you override one method like "void Mango.PrintName()" then the compiler show compile-time error like "CS0535 'Fruit' does not implement interface member 'Apple.PrintName()'" so you have to override both methods one for Mango and another one for Apple.


Similar Articles