Change exsting class to support multiple inheritance using interface in C#

Lets say you have class called MyInterfaceBase, along with this you need to derive another class to some base class.
In C# you don't have multiple inheritance. You can circumvent this limitation by using composition.

Define your interface like this :

public interface IMyInterface
{
    void MyAction();
}


Declare an abstract class with an abstract Function and implementing this interface:

public abstract class MyInterfaceBase : IMyInterface
{
    public void MyAction()
    {
        Function();
    }

    protected abstract void Function();
}

From this abstract class you can derive a concrete implementation. This is not yet your "final" class, but it will be used to compose it.

public class ConcreteMyInterface : MyInterfaceBase
{
    protected override void Function()
    {
        Console.WriteLine("hello");
    }
}


Now let's come to your "final", composed class. It will derive from SomeBaseClass and implement IMyInterface by integrating the functionality of ConcreteMyInterface:

public class SomeBaseClass
{
}

public class MyComposedClass : SomeBaseClass, IMyInterface
{
    private readonly IMyInterface _myInterface = new ConcreteMyInterface();

    public void MyAction()
    {
        _myInterface.MyAction();
    }
}


UPDATE

In C# you can declare local classes. This comes even closer to multiple inheritance, as you can derive everything within your composing class.

public class MyComposedClass : SomeBaseClass, IMyInterface
{
    private readonly IMyInterface _myInterface = new ConcreteMyInterface();

    public void MyAction()
    {
        _myInterface.MyAction();
    }

    private class ConcreteMyInterface : MyInterfaceBase
    {
        protected override void Function()
        {
            Console.WriteLine("hello");
        }
    }
}

Comments