How constructor chaining works in C Sharp (C#) - Performance & Efficiency
Constructor chaining lets one constructor call another in the same class to reuse code.
We want to see how the time to create an object grows as constructors call each other.
Analyze the time complexity of this constructor chaining example.
public class Box
{
public int Width, Height, Depth;
public Box() : this(1, 1, 1) { }
public Box(int size) : this(size, size, size) { }
public Box(int width, int height, int depth)
{
Width = width;
Height = height;
Depth = depth;
}
}
This code shows three constructors where simpler ones call the more detailed one.
Look for repeated calls or loops inside constructors.
- Primary operation: Calling another constructor using
this(...). - How many times: Exactly once per object creation, no loops or recursion.
The number of constructor calls stays the same regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 (calls and assignments) |
| 100 | 3 (calls and assignments) |
| 1000 | 3 (calls and assignments) |
Pattern observation: The work does not increase with input size; it stays constant.
Time Complexity: O(1)
This means creating an object with constructor chaining takes a fixed amount of time, no matter the input size.
[X] Wrong: "Constructor chaining makes object creation slower as input grows because of multiple calls."
[OK] Correct: The number of constructor calls is fixed and does not depend on input size, so time stays constant.
Understanding constructor chaining helps you write cleaner code and shows you know how object creation works under the hood.
"What if one constructor called another in a loop? How would the time complexity change?"