Constructor Chaining with this
Reuse initialization across constructors.
Why Chain Constructors?
When several constructors share setup logic, you can chain them so one calls another. This avoids duplicating code and keeps initialization in one place.
using System;
class Box
{
public int Width;
public int Height;
public Box(int width, int height)
{
Width = width;
Height = height;
}
public Box() : this(1, 1) { }
}
class Program
{
static void Main()
{
var def = new Box();
Console.WriteLine(def.Width + "x" + def.Height);
}
}The : this(...) Syntax
Chaining uses : this(args) after the constructor signature. The targeted constructor runs first, then the current body runs.
using System;
class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
Console.WriteLine("Full constructor ran");
}
public Person(string name) : this(name, 0)
{
Console.WriteLine("Name-only constructor ran");
}
}
class Program
{
static void Main()
{
var p = new Person("Sam");
Console.WriteLine(p.Name + ", " + p.Age);
}
}All lessons in this course
- Defining Constructors
- Constructor Chaining with this
- Object and Collection Initializers
- Static Constructors