October 6, 2016

Why Multiple Inheritance is not supported in C#/VB.Net?

As we know, Object oriented programming helps us to reuse common Data Members and Methods in different class with the help of Object Oriented Programming Concept called Inheritance.

In general, there are five types of inheritance –
  1. Single Inheritance
  2. Multiple Inheritance
  3. Hierarchical Inheritance
  4. Multilevel Inheritance
  5. Hybrid Inheritance

Among these, Multiple Inheritance is not supported in .Net.

What is Multiple Inheritance?
When a class acquires features from two or more base classes, it is called Multiple Inheritance.

Above diagram represents Multiple Inheritance example which is not supported in .Net. 

Let’s see now the reasons for this diamond problem – Why multiple inheritance is not supported in C#/VB.Net?

There is a possibility that Multiple Inheritance will cause ambiguity problems. It happens when two or more parent classes will have members with same identifier. Let’s understand this by an example.

In above example –

  1. Class A and Class B have same method called “Calculate(int val1, int val2)”.
  2. Class C inherits Class A & Class B. [.Net does not support this. It is shown here for example only].
  3. In Class C, we are trying to call a method from base class - “base.Calculate(10, 10)”.
  4. Now here, ambiguous situation arises. Compiler cannot identify which method to call, from Class A OR Class B.
  5. To avoid this situation, Multiple Inheritance is not supported in .Net.

So basically, Multiple Inheritance is not supported in .Net to avoid ambiguity. However, Interface is an alternate that can be used in .Net to avail Multiple Inheritance.

If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment