What is inheritance in C#

How to implement inheritance, what are the benifits of inheritance and types of inheritance

Category: C# Tags: C#


    Inheritance is required to derive features of base class into derived classes, for example, Father's resources are directly available to his son.


Benefits and Features

  1. Re-usability of existing code.
  2. Maintainability is the most use of inheritance, you not need to change your existing code.
  3. Code reduction is a great thing, you won't be writing same code multiple times.
public class Computer
public string Processor;
public int RAM;

    In above code we created an Computer class, suppose there are laptops and desktops sold by a company, both must have processor and ram but laptops have touchpad and desktops have mouse instead. So we created a Computer class as base class which is having common properties Processor and RAM. Now  create Laptop and Desktop classes below.

public class Laptop : Computer
public string TouchPad;
public class Desktop : Computer
public string Mouse;

    Here in above example we created Laptop and Desktop classes which are child classes of Computer class (for inheritance we use ':' to extend classes) because laptop and desktop having  different property touchpad, mouse respectively but common properties processor and ram, we could reuse computer class.

Now let's create object of Laptop and Desktop

static void Main(string[] args)
Laptop laptop = new Laptop();
Desktop desktop = new Desktop();

laptop.TouchPad = "hp";
desktop.Mouse = "moserbear";

Console.WriteLine("laptop touchpad: " + laptop.TouchPad);
Console.WriteLine("desktop mouse: " + desktop.Mouse);


laptop touchpad: hp

desktop mouse: moserbear

Types of Inheritance

  1. Single level(shown above).
  2. Multilevel.
  3. Multiple.
  4. Hierarchical.
  5. Hybrid.

I have explained first one already in above example.

2. Multilevel:

public class A
{ }
public class B:A
{ }
public class C:B
{ }

3. Multiple :
        This is not supported by C# in classes but we can do this using Interfaces, Like:

public interface I1
    int M1();
public interface I2
    string M2();
public interface I3 : I1, I2 { bool M3(); }

4. Hierarchical :

public class A
{ }
public class B:A
{ }
public class C:A
{ }

5. Hybrid :
        This is the mixture of all types of inheritance like:

public interface A
{ }
public interface B : A
{ }
public interface C : B
{ }
public interface D : B, C
{ }

Like 0 People
Last modified on 30 September 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 135
Questions: 12
Given Best Solutions: 12 *


nice article...
Like 1 Person on 21 May 2014

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User