OOPs Concept in C# - Inheritance



There are four main concepts present in OOPs

  • Inheritance 
  • Polymorphism
  • Encapsulation  
  • Abstraction

Today, we will discuss about the first OOPs concepts which is inheritance.

Inheritance

With inheritance we can use the variables or methods of one class into another class. Inheritance is very widely used concept of OOPs in C#. There are mainly two types of inheritance

  • Multiple Inheritance
  • Multi-Level Inheritance

Multiple Inheritance:

In multiple inheritance we can inherit from more than one class e.g. suppose there are three class A, B & C, so A can inherit from B & C. 

e.g.

public class A
{

}

public class B
{

}

public class C : B, A
{

}

Multiple class inheritance is not supported in C#.


Multilevel Inheritance:

In Multilevel inheritance B can inherit from A and C can inherit from B.

e.g.

public class A
{

}

public class B : A
{

}

public class C : B
{

}

Multilevel class inheritance is supported in C#.

With inheritance we can reuse the code of parent class in the base class.

e.g. if we have a parent class and child class then child class can inherit from parent class and use its data variables and methods.

    class Program
    {
            static void Main(string[] args)
            {        
                    child c = new child();
                    c.a = 20;
                    c.b = 10;
                    int result  = c.Addition();

                    Console.WriteLine(result.ToString());

                    result = c.subtraction();

                    Console.WriteLine(result.ToString());

                    Console.ReadLine();
            }
    }

    public class Parent
    {
        public int a;
        public int b;

        public int Addition()
        {
            return a + b;
        }

    }

    public class Child : Parent
    {

        public int subtraction()
        {
            return a - b;
        }

    }

So in the above example child is inheriting from Parent class and even though Child class do not have variable a & b still we can use them in the subtraction method of Child class as they are present in the Parent class.

We have created a object of Child class and we can call the method Addition with Child class object as we have inherited from Parent class in Child class. So by using inheritance we can achieve code re-usability.

The output of the above code will be 30 & 10.

So today, we have seen how we can achieve inheritance in C#, The other OOPs concepts we will discuss in my next post.

Thank You...….


For any issues regarding C# OOPs concepts please write to me on below mail Id and I will surely get back to you.