Sobes.tech
Middle+

What to do if two different interfaces with the same method names are implemented in one class?

sobes.tech AI

Answer from AI

In C#, explicit interface implementation is used to implement two interfaces with methods of the same name.

interface IFirst
{
    void DoSomething();
}

interface ISecond
{
    void DoSomething();
}

class MyClass : IFirst, ISecond
{
    // Implicit implementation (accessible directly through the class object)
    public void DoSomething()
    {
        // Actions for MyClass
    }

    // Explicit implementation of IFirst (accessible only through casting to IFirst)
    void IFirst.DoSomething()
    {
        // Actions for IFirst
    }

    // Explicit implementation of ISecond (accessible only through casting to ISecond)
    void ISecond.DoSomething()
    {
        // Actions for ISecond
    }
}

When using explicit interface implementation, it cannot be called directly through the class instance. You need to cast the instance to the interface type first:

MyClass myObject = new MyClass();

// Call implicit implementation
myObject.DoSomething();

// Call explicit IFirst implementation
IFirst firstInterface = myObject;
firstInterface.DoSomething();

// Call explicit ISecond implementation
ISecond secondInterface = myObject;
secondInterface.DoSomething();

Explicit implementation is used for:

  • Resolving name conflicts from different interfaces.
  • Hiding the interface method implementation from the class instance, making it accessible only through the interface.