C# Inheritance

The C# inheritance is a reusability mechanism where members of one class can be accessed by another class using parent and child relationships. The syntax of the inheritance in C# Programming language is as shown below.

<Access modifier> Class <child class> : <parent class>

Class A // A is a parent class.
{
    Class members
}
Class B: Class A // B is a child class
{
    Members of A can be accessed here
}

The Parent class also called a base or super, whereas child can also call as a derived or subclass.

C# Inheritance Example

Inheritance mechanism in C# allows the child class to access the parent members (except its private members) as if it is the member’s owner.

To implement inheritance in C#, the parent class constructor must be accessible to the child. It means we have to define parent constructor as public since a constructor defined without any modifier is private by default.

Let us see an example of implementing the C# inheritance.

using System;

namespace CSharp_Tutorial
{
    class Program
    {
        public Program()
        {
            Console.WriteLine("This is parent class constructor");
        }
        public void Test1()
        {
            Console.WriteLine("Test1 method");
        }
        public void Test2()
        {
            Console.WriteLine("Test2 method");
        }
    }
}

OUTPUT

C# Inheritance 1
using System;
using System.Collections.Generic;
using System.Text;

namespace CSharp_Tutorial
{
    class Program1:Program
    {
        public Program1()
        {
            Console.WriteLine("This is child class constructor");
        }
        void Test3()
        {
            Console.WriteLine("Test3 method");
        }
        static void Main()
        {
            Program1 p = new Program1();
            p.Test1(); p.Test2(); p.Test3();
            Console.ReadLine();

        }
    }
}

OUTPUT

C# Inheritance 2

In this C# inheritance example, Program is a parent class in which a constructor created along with two methods Test1() and Test2(). Next, Program1 is the one that is also having a constructor and a method Test3(). But here in cProgram1, members of Program are also inherited.

Now when we try to execute Program1, C# compiler first calls the constructor in child class. Simultaneously, the child constructor calls the parent constructor implicitly to initialize the parent variables so that the child can make use of the parent members.

Hence, the sequence of execution is parent class constructor, child constructor followed by child inherited methods and methods purely defined in it.

NOTE: If a parent class is also has a parent, the instance created for child will call its constructor. At the same time, its constructor will call the parent constructor. And this parent constructor will call the parent constructor of this parent and so on. And the execution starts from the parent on top towards the child classes.

Remember, a parent class cannot access child members that purely defined in the child itself.

Creating a reference to child in a parent class

C# Parent class cannot access child members, but we can create a reference to child in a parent.

We already learned earlier that reference is just a pointer variable to the instance, i.e., the reference doesn’t have any memory allocated to it. Still, it points to the memory of the instance. Even though we can create a reference to the child, using that parent class reference, we cannot access the child members, which are defined in it purely.

using System;

namespace CSharp_Tutorial
{
    class Program
    {
        public Program()
        {
            Console.WriteLine("This is parent class constructor");
        }
        public void Test1()
        {
            Console.WriteLine("Test1 method");
        }
        public void Test2()
        {
            Console.WriteLine("Test2 method");
        }
        static void Main()
        {
            Program p;
            Program1 p1 = new Program1();
            p = p1;
            p.Test1(); p.Test2();
            Console.ReadLine();
        }
    }
}

OUTPUT

C# Inheritance 3

Here, p is a local variable to Program, which is parent. Next, p initialized with the instance p1 of Program1, which is a child.

Now p is a parent variable that is un-initialized and does not have any memory allocated to it, whereas p1 is a child instance. Obviously, the instance will always allocate memory.

p initialized with p1. It means p is a reference to instance p1 using which we are accessing Parent class members but cannot access child members purely.

Finally, we can say that without creating an instance to the parent class, we can use the reference pointing to child instance to access the parent members.

Object class at the top of the parent hierarchy

Every class defined by the pre-defined classes present in the libraries or us will have a parent, i.e., Object in System namespace.

Members of the class Object are Equals, GetHashCode, GetType, ToString

Hence all the members of the Object are accessible from any.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3
{
  class Program1:Program
  {
    void Test3()
    {
      Console.WriteLine("Test3 method");
    }
    static void Main()
    {
      Object o = new Object();
      Console.WriteLine(o.GetType());
      Program p = new Program();
      Console.WriteLine(p.GetType());
      Program1 p1 = new Program1();
      Console.WriteLine(p1.GetType());
      Console.ReadLine();

    }
  }
}

OUTPUT

C# Inheritance 4

GetType is an Object member that can access from any class. GetType will get the fully qualified names of the particular instance.

Here, o is an instance of the object in System namespace. It means System.Object. Next, p and p1 are the instances of Program and Program1 respectively from ConsoleApp3 namespace and hence

ConsoleApp3.Program

ConsoleApp3.Program1

Types of Inheritance

Depending on the number of immediate parent classes that have for a child or the number of immediate child classes has for a parent, C# inheritance are two types.

  • Single Inheritance
  • Multiple Inheritance

If a class has one immediate parent, then it comes under the C# Single inheritance. In contrast, if a class has more than one immediate parent, it comes under the C# multiple inheritances. However, C# supports only single inheritance, and it doesn’t support multiple inheritances of classes.

If the parent class constructor is a parameterized constructor?

As we already know, when the child class instance created, child constructor implicitly calls the parent constructor. It happens only when the parent constructor is parameterless.

But if the C# parent class constructor is a parameterized one, child constructor cannot call the parent’s constructor. To overcome this problem, we should call it explicitly from the child class constructor and pass the arguments by using the base keyword.

using System;

namespace CSharp_Tutorial
{
    class Program
    {
        public Program(int a)
        {
            Console.WriteLine("Constructor of class Program is called: " + a);
        }
        public void Test1()
        {
            Console.WriteLine("Test1 method");
        }
        public void Test2()
        {
            Console.WriteLine("Test2 method");
        }
    }
}

OUTPUT

C# Inheritance 5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3
{
  class Program1:Program
  {
    public Program1(int b):base(b)
    {
      Console.WriteLine("Constructor of class Program1 is called");
    }
    void Test3()
    {
      Console.WriteLine("Test3 method");
    }
    static void Main()
    {
      Program1 p1 = new Program1(10);
      Console.ReadLine();
    }
  }
}

OUTPUT

C# Inheritance 6

Here in child Program1, the keyword base represents the parent class.

When instance p1 created, it calls Program1 constructor followed by Program constructor by passing argument b, which is 10.

Here, variable b defined can also access within the child class.

Implementing C# Inheritance in Real-time

In real-time, we come across the word entity, which is nothing but an object, and the data collected about that object. The entity is always associated with specific attributes.

An application can create by establishing a relation among different entities. For example, if we need to develop an application for school,

Student, Teaching staff, Non-teaching staff, Temporary staff would be the entities in general.

There will be some common attributes maintained for each entity.

C# Inheritance 7

Id, Name, Address, Phone are the common attributes for all the entities. So with those four entities, we can create a class called a person and make it a parent to all.

In the same way, coming to the staff, salary and designation would be the attributes. Staff can be useful as a parent for both teaching and non-teaching staff.

The above image depicts the way of implementing the concept of inheritance in developing a C# school application.