How to Use this for Constructor Chaining in C
Constructor chaining in C# is an approach that allows one constructor
to call another constructor within the same class using the
this keyword. This practice centralizes initialization
logic, prevents code duplication, and makes classes easier to maintain
across multiple overloads. In this guide, you will learn the syntax,
execution order, and practical implementation of constructor chaining
with this.
The Syntax of
the this Keyword in Constructors
In C#, the this keyword followed by parentheses
: this(...) is appended to the constructor's declaration,
just before the opening brace. This instructs the runtime to execute
another constructor matching the provided argument list before executing
the body of the invoking constructor.
public class Car
{
public string Make { get; }
public string Model { get; }
public int Year { get; }
// Primary constructor handling all assignments
public Car(string make, string model, int year)
{
Make = make;
Model = model;
Year = year;
}
// Overload providing a default value for 'year'
public Car(string make, string model) : this(make, model, DateTime.Now.Year)
{
}
// Overload providing default values for all properties
public Car() : this("Unknown", "Unknown")
{
}
}Execution Order
When a constructor delegates to another using
: this(...), the chained constructor executes first:
- The caller invokes the parameterless
new Car(). - The
Car()constructor delegates immediately toCar(string, string). - The
Car(string, string)constructor delegates toCar(string, string, int). - The body of
Car(string, string, int)executes and sets all properties. - Control returns to
Car(string, string)to execute its body (if any). - Control returns to
Car()to execute its body (if any).
Key Rules and Best Practices
- Forward to the Most Specific Constructor: Route simpler overloads with default values toward a "master" constructor that contains the actual property assignments and validation logic.
- Avoid Circular References: A constructor cannot
call itself or create an indirect cycle (e.g., Constructor A calls B,
which calls A). The C# compiler will detect this and generate error
CS0516. - Distinct from Base Chaining: The
thiskeyword chains constructors within the same class. To invoke a constructor in a parent class, use: base(...)instead.