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

C# Inheritance Example

The C# inheritance mechanism 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 the 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();

        }
    }
}
Access Methods 2

In this C# inheritance example, Program is a parent class in which a constructor is 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 the Program are also inherited.

Now when we try to execute Program1, the compiler first calls the constructor in the 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 C# Inheritance execution sequence is parent class constructor, child constructor followed by child inherited methods and methods purely defined in it.

NOTE: If a parent class also has a parent, the instance created for the 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’s classes.

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

Creating a reference to a child in a parent class

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

We already learned earlier that the 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

Create a reference to child class 3

Here, p is a local variable to C# Inheritance Program, which is a parent. Next, p is 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 for the parent class, we can use the reference pointing to the 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 the System namespace. It means System.Object. Next, p and p1 are the instances of Program and Program1, respectively, from the ConsoleApp3 namespace, and hence

ConsoleApp3.Program

ConsoleApp3.Program1

Types of Inheritance in C#

Depending on the number of immediate parent classes that have for a child or the number of immediate child classes 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, a class with more than one immediate parent comes under the C# multiple inheritances. However, C# supports only single inheritance, and it doesn’t support multiple inheritances of classes.

Is the parent class constructor a parameterized constructor?

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

But if the C# parent class constructor parameterizes, the child constructor cannot call the parent’s constructor. We should call it explicitly from the child class constructor to overcome this problem 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");
        }
    }
parameterized constructor 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();
    }
  }
}
C# Inheritance 6

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

When instance p1 creates, it calls the. Program1 constructor followed by the 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 will always associate with specific attributes.

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

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

Some of the common attributes maintain for each entity.

C# Inheritance 7

Id, Name, Address, and Phone are all entities’ common attributes. 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 how inheritance will implement in developing a C# school application.

Categories C#