Constructor Chaining in C#

By | December 25, 2017

Constructor chaining is an approach where a constructor calls another constructor in the same class or base class. It is very useful when we have a class that defines multiple constructors. Before knowing how to use constructor chaining in C#. Let’s first see why we need constructor chaining.

Example: we have a class call “Employee” and this class consist of 4 constructor as below:-

class Employee
{
 private string _name;
 private string _email;
 private string _mobile;
 private string _address;
 public Employee(string Name)
 {
 this._name = Name;
 }
 public Employee(string Name, string Email)
 {
 this._name = Name;
 this._email = Email;
 }
 public Employee(string Name, string Email, string Mobile)
 {
 this._name = Name;
 this._email = Email;
 this._mobile = Mobile;
 }
 public Employee(string Name, string Email, string Mobile, string Address)
 {
 this._name = Name;
 this._email = Email;
 this._mobile = Mobile;
 this._address = Address;
 }
}

You can see in above code that there is an issue of duplicate code. Here we are duplicating the same code like “this._name = Name;” in all the constructor. This is the case where constructor chaining is very useful.

With the help of constructor chaining, we will eliminate the duplicate code issue in below example:

class Employee
{
private string _name;
private string _email;
private string _category;
private string _publication;

public Employee(string Name)
{
this._name = Name;
}
public Employee(string Name, string Email) : this(Name)
{
this._email = Email;
}
public Employee(string Name, string Email, string Mobile) : this(Name, Email)
{
this._mobile = Mobile;
}
public Employee(string Name, string Email, string Mobile, string Publication) : this(Name, Email, Mobile)
{
this._address = Address;
}
}

In the above code you can see that each constructor is calling another constructor using “this” keyword. So we don’t need to write code for assigning the values again and again. Here using “this” is similar to using “:base()”.

I hope you will enjoy the Constructor Chaining in C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome

Like it? Share it