Skip to main content

Inheritance from multiple interface with the same method name in C#


Hello Friends,

This article gives an idea about the situation called interface clash. This situation occurs when two interfaces have functions with the same name and signature and one base class implements these interfaces.

When two interfaces have functions with the same name and a class implements these interfaces, then we have to specifically handle this situation. We have to tell the compiler which class function we want to implement. For such cases, we have to use the name of the interface during function implementation.
Have a look at the following example:

CLASS


public class MyClass : IMyInterface1, IMyInterface2
{
    string IMyInterface1.DoSomething()
    {
        return "IMyInterface1";
    }

    string IMyInterface2.DoSomething()
    {
        return "IMyInterface2";
    }

    public string DoSomething()
    {
        return "MyClass";
    }
}

CODE C#:

MyClass ObjMyclass = new MyClass();
//implicit implementation
Console.Write("" + ObjMyclass.DoSomething());
// explicit implementation
// this method will be called if you have a reference to an IMyInterface1 and IMyInterface2
Console.Write("" + +((IMyInterface1)ObjMyclass).DoSomething());
Console.Write(""+ ((IMyInterface2)ObjMyclass).DoSomething());

OUTPUT

MyClass
IMyInterface1
IMyInterface2

Comments