Why C# does not support multiple class inheritance?
or
What are the problems of multiple class inheritance?
C# does not support multiple class inheritance because of the diamond problem that is associated, with multiple class inheritance. Let us understand the diamond problem of multiple class inheritance with an example.
As shown in the image above:
1. I have 2 classes - ClassB and ClassC
2. Both of these classes inherit from ClassA
3. Now, we have another class, ClassD which inherits from both ClassB and ClassC
So, if a method in ClassD calls a method defined in ClassA and ClassD has not overriden the invoked method. But both ClassB and ClassC have overridden the same method differently. Now, the ambiguity is, from which class does, ClassD inherit the invoked method: ClassB, or ClassC?
In order not to have these problems, C# does not support multiple class inheritance.
or
What are the problems of multiple class inheritance?
C# does not support multiple class inheritance because of the diamond problem that is associated, with multiple class inheritance. Let us understand the diamond problem of multiple class inheritance with an example.
Here is a youtube video on Problems of multiple class inheritance |
As shown in the image above:
1. I have 2 classes - ClassB and ClassC
2. Both of these classes inherit from ClassA
3. Now, we have another class, ClassD which inherits from both ClassB and ClassC
So, if a method in ClassD calls a method defined in ClassA and ClassD has not overriden the invoked method. But both ClassB and ClassC have overridden the same method differently. Now, the ambiguity is, from which class does, ClassD inherit the invoked method: ClassB, or ClassC?
In order not to have these problems, C# does not support multiple class inheritance.
use virtual inheritence
ReplyDeleteVirtual inheritance is a concept of c++. If it is applicable in c# please publish it
DeleteVirtual Inheritance means to inherits Class A as virtually..it is only applicable in C++ not in C# and Java
ReplyDeletemake sense not to have multiple inheritance in c#. if the .net framework will support it, so does all language that uses the framework (vb, j++, f#... etc). bottom line is, the cost does not justify the means.
ReplyDeleteWhat happens if multiple inheritance condition arise in interface?
ReplyDeleteIf the multiple interfaces have the same methods and implemented in a single class, we have to explicitly implement the interfaces. Venkat has provided the great example on it. Checkout that video.
DeleteUse explicit implementation of Interfaces. Check out the video of Venkat on explicit implementation.
Delete