Inheritance Object Oriented Programming in c#

 Inheritance is an important pillar of OOP(Object Oriented Programming). 

It is the mechanism in C# by which one class is allowed to inherit the features(fields and methods) of another class.


Example

we are humans we have such as the ability to speak, breathe, eat, drink, , see people around you etc. so parent class is Human which are inherit base class like speak ,eat  etc.

public class Human
{
public void BodyPart()             
               {
Console.WriteLine("This is Human Body class");
}
}
public class Eat : Human
{
   public void BaseInher()
   {
Console.WriteLine("I can inheritance from Parent class");
   }
}
public class Solution
{
        public static void Main()
        {   
                        Eat a=new Eat();
a.BodyPart();
a.BaseInher();
        }
} 

Output
 This is Human Body class
I can inheritance from Parent class



Advantage

 1. The idea of reusability. One can derive a new class (sub-class) from an existing class and add new features to it without modifying its parent class. There is no need to rewrite the parent class in order to inherit it.



Types of Inheritance in C#

Single Inheritance 
 in which there is one base class and one derived 



public class A    //base class    
{  
    public float salary = 4000;
}  
public class B: A     //derived class    
{  
    public float bonus= 6000;
}  
class Program {  
       public static void Main(string[] args)  
        {  
            A p1 = new A();  
  
            Console.WriteLine("Salary: " + p1.salary);  
            Console.WriteLine("Bonus: " + p1.bonus);  
  
        }  

Output 
Salary 4000
Bonus 6000


Hierarchical Inheritance :



class A  //base class    
{  
    public string msg()  
    {  
        return "this is A class Method";  
    }  
}  
class B : A  
{  
    public string info()  
    {  
        msg();  
        return "this is B class Method";  
    }  
    class C : A  
    {  
        public string getinfo()  
        {  
            msg();  
            return "this is B class Method";  
        }  
    }  
}    

Multiple Inheritance(Through Interfaces)






Does C# support multiple class inheritance?

No, C# supports single class inheritance only.


Are constructors and destructors inherited ?

No


Is multiple inheritance possible in C# Why?
No. because


a) Its not supported by CLR since its support many diff language and not all languages can have multiple inheritance concept. 


b)Because of the complexities involved where method name can clash when two diff classes have same method name. This is resolved by pointers in C++ but its not possible in c#.

Do structs support inheritance?


No, structs do not support inheritance, but they can implement interfaces.