Inheritance in C# using an example

 

Definition of Inheritance


Inheritance means parent-child relationship.By using Inheritance methodology we can create a new class by using existing class code (i.e. reuse existing methods, properties etc).It also referred to as reusability of the code so by using Inheritance we can reuse the code again and again.

What We Call

In Inheritance main existing class is called as generalized class, base class, super class and parent class and the new class created from existing class is called as specialized class, sub class, child class and derived class. We normally talk in terms of base class and derived class.

Syntax of Inheritance

 
class ParentClass{

...parent class code

}

class ChildClass : ParentClass{
...child class code
}

Special Character ":" in Inheritance

Inheritance uses special character called ":" colon to make a relationship between parent and child as you can see in above syntax of code.

When to Implement Interitance

When we create a new class and we want to reuse some of the methods or properties from existing class then that is an ideal time to implement inheritance.

Advantage of Interitance

Reusability of the code.

 

Types of inheritance in c#


There are 5 types of inheritance as shown below.

1.Single Inheritance
2.Multilevel Inheritance
3.Multiple Inheritance
4.Hierarchical Inheritance
5.Hybrid Inheritance

Single Inheritance

Single Inheritance means when a single base is been implemented to single derived class is called as Single Inheritance.Means we have only one parent class and one child class.

Example of Single Inheritance

 
class Company{

  public void CompanyName(){

   Console.WriteLine("Name of the Company");

  }

  public void CompanyAddress(){

   Console.WriteLine("Address of the Company");

  }

}

class Employee : Company {
 
   public void NameofEmployee(){
   
      Console.WriteLine("Name of the Employee");	
	
   }

   public void Salary(){

      Console.WriteLine("Salary of the Employee");

   }

}

As you can see from the above code that we have implemented single inheritance.

 

Multilevel Inheritance

When a derived class is created from another derived class or let me put it in this way that a class is created by using another derived class and this type of implementation is called as multilevel Inheritance


Example of Multilevel Inheritance

 
class HeadOffice{

  public void HeadOfficeAddress(){
    
   Console.WriteLine("Head Office Address");

  }
}

Now let's assume that class "HeadOffice" is our Parent class or Base class. Now in my next step i will create one derived class.

 
class BranchOffice : HeadOffice{

  public void BranchOfficeAddress(){
    
   Console.WriteLine("Branch Office Address");

  }

}

So as you can see that i have created a derived class "BranchOffice" by implementing the class "HeadOffice" to it.

It means now we have one parent class and one derived class. In the next step i will create another derived class by implementing our existing derived class "BranchOffice" to achieve multilevel Inheritance.

 
class Employee : BranchOffice {
 
   public void NameofEmployee(){
   
      Console.WriteLine("Name of the Employee");	
	
   }

   public void Salary(){

      Console.WriteLine("Salary of the Employee");

   }

}

From the above souce code you can see that we have achieved multilevel Inheritance by implementing one derived class to another derived class. Now the class "Employee" will have the access of all the properties and methods of class "BranchOffice" and class "HeadOffice".

Multiple Inheritance

Due to the complexity of a code multiple inheritance is not been supported in C# or in DOT.NET but DOT.NET or C# supports multiple interfaces.

Hierarchical Inheritance

When more than one derived classes are implemented from a same parent class or base class then that type of implentation is known as hierarchical inheritance.

In short it means single base class having more than one derived classes.

 

 
class HeadOffice{

  public void HeadOfficeAddress(){
    
   Console.WriteLine("Head Office Address");

  }
}


class BranchOffice1 : HeadOffice{

  public void BranchOfficeAddress(){
    
   Console.WriteLine("Branch Office Address");

  }

}

class BranchOffice2 : HeadOffice{

  public void BranchOfficeAddress(){
    
   Console.WriteLine("Branch Office Address");

  }

}

As you can see from above the code that we have one base class "HeadOffice" and two derived classes "BranchOffice1" and "BranchOffice2" which are implemented from same base class i.e. "HeadOffice".

Hybrid Inheritance

This is a special type of inheritance and can be achieved from any combination of single, hierarchical and multi level inheritance known as hybrid inheritance.

In the below code example i have combined hierarchical inheritance and multi level inheritance together.

 
//This part of code is related to hierarchical inheritance
class HeadOffice{

  public void HeadOfficeAddress(){
    
   Console.WriteLine("Head Office Address");

  }
}


class BranchOffice1 : HeadOffice{

  public void BranchOfficeAddress(){
    
   Console.WriteLine("Branch Office Address");

  }

}

class BranchOffice2 : HeadOffice{

  public void BranchOfficeAddress(){
    
   Console.WriteLine("Branch Office Address");

  }

}

 

 
////This part of code is related to combination of hierarchical inheritance and multi level inheritance

class Employee : BranchOffice2  {
 
   public void NameofEmployee(){
   
      Console.WriteLine("Name of the Employee");	
	
   }

   public void Salary(){

      Console.WriteLine("Salary of the Employee");

   }

}

So that you have understood the inheritance and their 5 types. Now let's a simple example of inheritance using csharp.

Example of Inheritance using C#

 
   public class Car{
        private string rearviewmirror;
        private string gear;
        private string clutch;
        private string steering;

        public string RearViewMirror
        {
            get { return rearviewmirror; }
            set { rearviewmirror = value; }
        }

        public string Gear
        {
            get { return gear; }
            set { gear = value; }
        }

        public string Clutch
        {
            get { return clutch; }
            set { clutch = value; }
        }

        public string Steering
        {
            get { return steering; }
            set { steering = value; }
        }

        public virtual void CarPrice()
        {
            Console.WriteLine("Car Prize is : 0");
        }

        public virtual void NameofCar()
        {
            Console.WriteLine("Company Name of this Car is -- ");
        }


    }

Above i have created a simple class "Car" with some methods and some properties. Now next step i will create two classes "SentroCar" and "BCWCar" and implement it with a single base class "Car"

Derived Class 1 implemented with base class Car

 

 
   public class SentroCar:Car
    {

        public override void CarPrice()
        {
            Console.WriteLine("Car Prize is : 2.5L INR");
        }
        public override void NameofCar()
        {
            Console.WriteLine("Company Name of this Car is Sentro");
        }
    }

Derived Class 2 implemented with base class Car

 

    
    public class BCWCar : Car
    {
    
        public override void CarPrice()
        {
            Console.WriteLine("Car Prize is : 4.5L INR");
        }
        public override void NameofCar()
        {
            Console.WriteLine("Company Name of this Car is BCW ");
        }
    }

As you see that we have two derived classes implemented from same base class. This type of implementation can also be called as Hierarchical Inheritance.

Output by Using Console Application

 
class Program
    {
        static void Main(string[] args)
        {

            Car obj = new SentroCar();
            obj.CarPrice();
            obj.NameofCar();
  
            Car obj = new BCWCar();
            obj.CarPrice();
            obj.NameofCar();
        }
    }

//Output
Car Prize is : 2.5L INR
Company Name of this Car is Sentro

Car Prize is : 4.5L INR
Company Name of this Car is BCW.

So this all about the inheritance. if you guys have any doubts or any query kindly let me and drop your valuable feedbacks.

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
May
03
2013

OOPS Principle - Encapsulation in C# with an example

CLICK TO READ FULL ARTICLE

Views - 114567 |Category - C#

Apr
30
2013

Explain the copy and private constructor with an example in C#

CLICK TO READ FULL ARTICLE

Views - 52096 |Category - C#

Apr
29
2013

Types of Access Modifiers in C#

CLICK TO READ FULL ARTICLE

Views - 22321 |Category - C#

Apr
24
2013

Difference Between Array and Array List in C#

CLICK TO READ FULL ARTICLE

Views - 41358 |Category - C#

Apr
22
2013

How to Create and Initialize Jagged Arrays using C#

CLICK TO READ FULL ARTICLE

Views - 20148 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

kbb5o

 

 
Comments

Posted by Chinna on 2016-05-27

Hello, Once check single Inheritance block diagram...... May be its wrong

Posted by Devaraj on 2015-12-08

in the above mentioned wat re we doing with that steering , mirror, gear ,clutch all that method wat does it do n the program??

Posted by Piku on 2015-10-19

single level inheritance example "Company and Employees" is not a correct example. when we talk about inheritance, then it should follow IS-A relationship. like "Car IS A Vehicle" then Vehicle is base class and car is derived class.

Posted by Shilpa on 2015-04-16

thanks for explaining

Posted by Chandrababu on 2014-11-22

As per my knowledge this site is so much helpful for C# biggeners. Dude your helping so many people without expecting anything keep it up :)

Posted by Naidu on 2014-09-11

very clear and good explained...

Posted by Uma Maheswari on 2014-08-08

Good Explanation Beginners can easily understand.. Nice job.. Very useful site..

Posted by Pravin on 2014-07-31

It is not possible to implement multilevel inheritance in interface

Posted by Vicky on 2014-07-30

very clear and good explained....

Posted by BC on 2014-07-11

good guide... may benefit if c # example had sub classes with additional properties and functions, then show application using sub class, but calling methods in both sub and super class... well received, helped my understand....

Posted by Eswar on 2014-06-13

multilevel Inheritance possible with interfaces

Posted by Ravindera on 2014-06-05

Good explanation

Posted by Yasar on 2014-04-22

csharp interview ask pattern

Posted by Vinay on 2014-04-01

very helpful but can you please explain Inheritance with access modifiers

Posted by Reema on 2014-03-25

easy to understand and helpful this topic

Posted by Prasanth on 2013-10-19

this is used

Posted by Sindhura on 2013-09-30

Good Post!! easy to understand

Posted by S.jitendra on 2013-09-18

in my program i am not able to inherit class it showing error that the type or namespace could not found what is it mean for parent class

Posted by MOHAN DOSS on 2013-07-09

hi..your explanation is so good... plz give the output for each program... then only understand 100%..

Posted by Gopi reddy k on 2013-06-27

This topic is more helpful to me.........complete opps material send me my mail plez