Constructor chaining in C# means calling one constructor from another within the same class or from a base class. It helps reuse initialization code and keeps the class clean by avoiding repetition. Constructor chaining is done using the keywords this and base.
- Constructor chaining allows reusing existing constructor logic.
- this is used to call another constructor in the same class, while base is used to call a constructor of the parent class.
- Chaining must be the first statement inside the constructor.
- Helps avoid code duplication and makes initialization consistent.
1. Chaining with this Keyword
When a class has multiple constructors, one constructor can call another in the same class using this.
using System;
class Student {
string name;
int age;
// Constructor with one parameter
public Student(string name) {
this.name = name;
Console.WriteLine("Name: " + name);
}
// Constructor with two parameters, chaining to first
public Student(string name, int age) : this(name) {
this.age = age;
Console.WriteLine("Age: " + age);
}
public static void Main() {
Student s1 = new Student("Amit");
Student s2 = new Student("Sita", 21);
}
}
Output:
Name: Amit
Name: Sita
Age: 21
2. Chaining with base Keyword
If a class inherits another class, a constructor in the child class can call the constructor of the base class using base.
using System;
class Person {
// Base class constructor
public Person(string name) {
Console.WriteLine("Person Constructor: " + name);
}
}
class Employee : Person {
// Derived class constructor chaining to base class constructor using 'base'
public Employee(string name, int id) : base(name) {
Console.WriteLine("Employee Constructor: Id = " + id);
}
public static void Main() {
Employee emp = new Employee("Rahul", 101);
}
}
Output:
Person Constructor: Rahul
Employee Constructor: Id = 101
3. Multiple Levels of Chaining
Constructors can chain across multiple levels in the hierarchy, ensuring initialization happens in order.
using System;
class A {
// Base class constructor
public A() {
Console.WriteLine("Class A Constructor");
}
}
class B : A {
// Derived class B constructor chaining to base class A
public B() : base() {
Console.WriteLine("Class B Constructor");
}
}
class C : B {
// Derived class C constructor chaining to base class B
public C() : base() {
Console.WriteLine("Class C Constructor");
}
public static void Main() {
// Creating object of C triggers constructors in order: A -> B -> C
C obj = new C();
}
}
Output:
Class A Constructor
Class B Constructor
Class C Constructor
Rules for Constructor Chaining
- Chaining must be the first statement in the constructor body.
- Only one constructor can be chained at a time.
- You can use this for same class chaining or base for parent class chaining.
- If no constructor is explicitly chained, the compiler calls the default base constructor automatically.
Note: Constructor chaining must not be circular, calling one constructor that eventually calls itself will cause a compile-time error.