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 class or super class, whereas child class can also call as a derived class or subclass.

C# Inheritance Example

Inheritance mechanism in C# allows the child class to access the parent class 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 class. It means we have to define parent class 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 a class that is also having a constructor and a method Test3(). But here in class Program1, members of class Program are also inherited.

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

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

NOTE: If a parent class is also has a parent class, the instance created for child class 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 class members that purely defined in the child class itself.

Creating a reference to child class in a parent class

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

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 class, using that parent class reference, we cannot access the child class 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 class Program, which is parent class. Next, p initialized with the instance p1 of class Program1, which is a child class.

Now p is a parent class variable that is un-initialized and does not have any memory allocated to it, whereas p1 is a child class 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 class members purely.

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

Object class at the top of the parent class hierarchy

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

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

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

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 class 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 class in System namespace. It means System.Object. Next, p and p1 are the instances of Program and Program1 classes 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 class or the number of immediate child classes has for a parent class, C# inheritance are two types.

  • Single Inheritance
  • Multiple Inheritance

If a class has one immediate parent class, then it comes under the C# Single inheritance. In contrast, if a class has more than one immediate parent class, 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 class constructor implicitly calls the parent class constructor. It happens only when the parent class constructor is parameterless.

But if the C# parent class constructor is a parameterized one, child class 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 class 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 class to all.

In the same way, coming to the staff class, salary and designation would be the attributes. Staff class 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.