Constructor Chaining in C#

Ever wondered whether you can inherit constructors? Well, here’s all you need to know about it.

Is Constructor Inheritance possible? Why or why not?

Constructors cannot be inherited in C# mainly because if that happens, we won’t be able to correctly determine how the objects of our derived classes are instantiated. Another problem that could occur in this case is the possibility of the object being initialized incorrectly if the constructor is not redefined as multiple derived classes would be able to use parent class constructor implicitly.

Constructors can hence not inherit but can be called from the constructors of the derived child class using what is called Constructor Chaining.

What is Constructor Chaining?

Constructor Chaining is the process of connecting multiple classes that are related to each other by inheritance. When the instance of the class is created, the constructor from that class calls another constructor from the same class by using ‘this’ keyword or from the parent class using the keyword ‘base’. 

Syntax

The syntax for Constructor Chaining is as follows:

1. When Derived or Child Class Constructor calls the Base or Parent Class Constructor-

Derived Class:

public Constructor (Parameter param1) : base (param) {
}

Base Class:

public Base (Parameter param1) {
Init(param1);
}

2. When a Constructor calls another Constructor from the same class-

Constructor that inherits:

public Constructor (Parameter param1) : this (param) {
}

Constructor that is inherited from:

public Constructor (Parameter param1, Parameter param2) {
}

Note: Here in the 2nd case, both the constructors belong to the same class and hence have the same name. Also, the two constructors in this case have different number of parameters as both constructors already have the same name, if they were to also have same parameters, duplication would occur.

Order of Execution of Constructors

Let us look at a simple modal example:

public class ExampleClass
{  
    public ExampleClass (): this(100)  
        {  
            //Constructor 1: constructor that inherits
    	    Console.WriteLine("Constructor 1 Called");
        }  
                
    public ExampleClass (int id)   
        {  
            //Constructor 2: Constructor that is inherited from
	    Console.WriteLine("Constructor 2 Called");
        }  
 }  

In the above code, ‘this(100)’ part will actually execute the 2nd constructor i.e. ‘public ExampleClass (int id)’ constructor first and hence ‘Constructor 2 called’ will be printed first followed by ‘Constructor 1 called’. This happens because ‘this(100)’ is an initializer that, as the name suggests, initializes or calls a method. There can only be one initializer like this in a method.

Now let us see how this order of execution for the above code occurs. If we create an instance of the ExampleClass as follows –

ExampleClass ec = new ExampleClass()

then the execution of ExampleClass (int id) will happen before ExampleClass. This means that the output of:

public ExampleClass(): this(100)  
 {  
   //Constructor that inherits
   Console.WriteLine("Constructor 1 Called");
 }  

will be the same as –

public ExampleClass()  
{  
   ExampleClass(100)    
   Console.WriteLine("Constructor 2 Called");
}   

C# Example using Constructor Chaining

Constructor Chaining is very useful when there is a class which defines multiple constructors. Let us take a real world example to properly understand when and how to make use of Constructor Chaining.

Let us consider a class ‘Employee’. This Employee class has 3 constructors. Each constructor needs to validate the Employee Id of the employees in order to categorize each one of them.

For this situation, if we go by the normal approach, our code will look somewhat like the code below –

     Class Employee
     {
	string _empCategory = “ “;
        string _empId = “ ”;
        string _empName = “ “;
        string _empAddress = “ “;

        //constructor 1
        public Employee(string empId) {
	  _empCategory = “<employee_category>”;
	  _empId = empId;
        }

        //constructor 2
        public Employee(string empId, string empName) {
	    _empCategory = “<employee_category>”;
	    _empId = empId;
            _empName = empName;
        }

        //constructor 3
        public Employee(string empId, string empName, 
                        string empAddress) 
        {
	    _empCategory = “<employee_category>”;
	    _empId = empId;
            _empName = empName;
            _empAddress = empAddress;
        }
    }

As we can see, this code resolves our issue but it duplicates the current code because we are assigning values to our Employee Id in all the constructors.

This issue of duplication of code can be easily resolved if we use Constructor Chaining. In this case, we assign Employee Id value only to the one constructor that has the most number of parameters and this constructor can be called when the other 2 constructors are being called.

The code below shows how –

    Class Employee
    {
	string _empCategory = “ “;
        string _empId = “ ”;
        string _empName = “ “;
        string _empAddress = “ “;

        //constructor 1
        public Employee(string empId) : this(empId, “ “, “ “)  {
        }

        //constructor 2
        public Employee(string empId, string empName) 
                       : this(empId, empName, “ “) {
        }

        //constructor 3
        public Employee(string empId, string empName, 
                        string empAddress) {
	   _empCategory = “<employee_category>”;
	   _empId = empId;
           _empName = empName;
           _empAddress = empAddress;
       }
}

One thing that we need to note here is that if we do not use the keyword ‘this’, then by default it will be considered that we are calling the base class constructor which is same as using the ‘base’ keyword in the code.

C# Classes that use Constructor chaining

Below is an example or HashSet class under System.Collections.Generic Namespace that use Constructor chaining

        public HashSet(int capacity) 
               : this(capacity, EqualityComparer<T>.Default) { }
 
        public HashSet(int capacity, IEqualityComparer<T> comparer)
        {
           //Initialization Code
        }

The above source code of HashSet can be checked at Microsoft site here

Conclusion 

Using Constructor Chaining is a great practice mainly because –

1. Helps to avoid code duplication.

2. Helps to encapsulate the code well.

Both of which are very important and helpful in the long run.

Leave a Comment

Your email address will not be published.