What is Diamond Problem in C#?
I hope you have already came across questions such as why C# doesn’t support multiple inheritance, why multiple inheritance is not supported in C# etc. One of the main reason behind this is Diamond Shape Problem. You can learn better about this problem with an example. Suppose you have 4 classes named as A, B, C, and D. A is your main base class. A contains a virtual method named as PrintName. Because it is virtual method, all classes which will inherit from base class A, can override this method. B and C are 2 classes, which are inheriting from base class A and overriding its PrintName method. The class D is inheriting from both B and C, which means both the overridden methods are available for class D.
Now, there is a question. When you create an instance of D class and would try to call method PrintName, which method should be called? Method from B or C? There will be an ambiguity and this problem is called Diamond Problem.
The code given below is just for demonstration purpose only.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hello { class A { public virtual void PrintName() { Console.WriteLine("Class A"); } } class B:A { public override void PrintName() { Console.WriteLine("Class B"); } } class C:A { public override void PrintName() { Console.WriteLine("Class C"); } } //NOT WORK class D: B, C { } class Program { static void Main(string[] args) { D d = new D(); d.PrintName(); } } }