What is the Constructor Chaining in C#?

Asked 19-Dec-2017
Viewed 753 times

1 Answer


1

What is the Constructor Chaining in C#?

Constructor chaining is an approach to connect two or more classes in a relationship as Inheritance. In Constructor Chaining, one constructor invoked from another constructor implicitly by base keyword so when you create an instance of the child class to it will call parent's class Constructor without it inheritance is not possible. Or in other words, every child class Constructor is mapped to parent class Constructor.

We can also say that Constructor Chaining is an approach where a Constructor invokes another constructor in the base or same class.
During development of a product, when we have a class that defines multiple constructors. Assume we are developing a class Employee. And this class has three constructors. On each constructor, we have to validate the Employee's ID and department. Now if we do not use the constructor chaining approach, its redundancy is very high as follows:
class Employee

 {
 string _department="";
 string _id="";
 string _fName="";
 string _lName="";

 public Employee(string id)
  {
  _department="<Employee_Department>";
  _id=id;
  }


 public Employee(string id,string fName)
  {
  _department="<Employee_Department>";
  _id=id;
  _fName=fName;
  }


 public Employee(string id,string fName,string lName)
  {
  _department="<Employee_Department>";
  _id=id;
  _fName=fName;
  _lName=lName;
  }
 }
The above approach solves our problem. But its increase code redundancy. Hence, Now we use Constructor Chaining.

class Employee
 {
 string _department="";
 string _id="";
 string _fName="";
 string _lName="";

 public Employee(string id)
  :this(id,"","") {

  }


 public Employee(string id,string fName)
  :this(id,"fName","") {

  }


 public Employee(string id,string fName,string lName)
  {
  _department="<Employee_Department>";
  _id=id;
  _fName=fName;
  _lName=lName;
  }
 }

Hope its informative...