DEV Community

Ranganath-Prasad
Ranganath-Prasad

Posted on

The Diamond problem - C# Multiple inheritance

Since the day i started learning C#, i knew

Multiple inheritance is NOT supported through classes, but, the same can be achieved through interfaces
.

But i never bothered to explore the reason behind this.

Glad that it came up in my mind last week and i started looking for an answer - the reason behind C# NOT supporting Multiple inheritance is because of the diamond problem.

For a moment, assume C# support Multiple inheritances through classes and see the below class diagram

class diagram

As you can see above :

1) Class A has a method named 'Test' marked as Virtual

2) Class B inherits Class A and Overrides 'Test' method

3) Class C also inherits Class A and Overrides 'Test' method

4) Class D inherits both Class B and Class C

Now, can you guess which Test method does Class D inherit ? The one from Class B or the one from Class C ? CAN'T tell right? This is called as The Diamond Problem.

If above class diagram is not clear, see code below :


using System;

public class A
{
    public virtual void Test() { Console.WriteLine("This is class A"); }
}

public class B : A {
    public override void Test() { Console.WriteLine("This is class B"); }
}

public class C : A
{
    public override void Test() { Console.WriteLine("This is class C"); }

}

public class D : B, C {

}

public class Program
{
    public static void Main()
    {
        new D().Test();      // What will be the output ?
    }

}
Enter fullscreen mode Exit fullscreen mode

But, how come it supports Multiple inheritance through Interfaces ? you might ask.

That's because, Interface methods are abstract by default, they don't have implementation. And since interfaces does NOT have implementation, any class that inherits more than one interface will implement the interface methods through Explicit interface implementation.

You might be thinking that C# 8 has default interface implementation and that might cause the diamond problem. It DOESN'T. You can try it.

Your comments are always welcome :)

Top comments (0)