C# Inheritance

In C#, Inheritance is a mechanism by which one object acquires all the properties of another object automatically. The object which is inheriting the other object is called chilled object while the one which is inherited is called parent object. The chilled object can reuse, redefine all the properties and behavior of its parent object. The class which inherits another class to access its members is called derived class while the class which is inherited is called base class.


Advantages of inheritance:
  1. Code reusability: the code which is written in the base class can be reused in the derived class
  1. Code Extensibility: inheritance provides flexibility to extend the code according to the business logic in the derived class.
  1. Removes Code Redundancy: Inheritance removes code redundancy by inheriting all the logic which was once written. We don't need to write the logic again and again.
Types of inheritance in C#:
  1. Single level inheritance
  2. Multilevel inheritance
Note: C# doesn't support multiple inheritance by class.

C# Single Level Inheritance Example: inheriting Fields
using System;
public class Bank
{
                        public float R_O_I=6;
}
public class SBI:Bank
{
                        public float share_price=1300;
}
public class Inheritance_Example1
{
                        public static void Main(string[] args)
                        {
                                    SBI bank=new SBI();
                        Console.WriteLine("Rate of interest of SBI is "+bank.R_O_I+" and The share price      is "+bank.share_price);
                        }
}
Output Rate of interest of SBI is 6 and The share price is 1300

C# Single Level Inheritance Example: Inheriting Methods
using System;
public class Animal 
{
                        public void eat()
                        {
                        Console.WriteLine("Eating.....");
                        }
}
public class Hourse:Animal
{
                        public void run()
                        {
                        Console.WriteLine("Running......");
                        }
}
public class InheritanceExample2
{
                        public static void Main (string[] args)
                        {
                                    Hourse h=new Hourse();
                                    h.eat();
                                    h.run();
                        }
}
Output Eating..... Running......



ADVERTISEMENT
ADVERTISEMENT