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:

  1. The caller invokes the parameterless new Car().
  2. The Car() constructor delegates immediately to Car(string, string).
  3. The Car(string, string) constructor delegates to Car(string, string, int).
  4. The body of Car(string, string, int) executes and sets all properties.
  5. Control returns to Car(string, string) to execute its body (if any).
  6. 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 this keyword chains constructors within the same class. To invoke a constructor in a parent class, use : base(...) instead.