Wednesday, February 15, 2023

Can we inherit multiple classes?

No, multiple inheritances are not supported in .Net. 


But we can achieve this using implementation of multiple interface.

Example:

There are two Parent classes Paretn1 and Parent2. This is inherited by the Child class, In the GetData() method, the child calls the parent class method PrintData()

In this case which method will be executed? It is very difficult for CLR to identify which method to call. It shows that multiple inheritances create ambiguity in the oops concept. In order to avoid this ambiguity we are going for multiple interface implementations.


           
public class Parent1
    {
        public string PrintData()
        {
            return "This is parent1";
        }
    }
    public class Parent2
    {
        public string PrintData()
        {
            return "This is parent2";
        }
    }

    public class Child1 : Parent1, Parent2
    {
        public string GetData()
        {
            return this.PrintData();
        }
    }


No comments:

Post a Comment