What is the Constructor Chaining in C#?

Technology CommunityCategory: C#What is the Constructor Chaining in C#?
VietMX Staff asked 3 years ago

Constructor Chaining is an approach where a constructor calls another constructor in the same or base class. This is very handy when we have a class that defines multiple constructors.

Consider:

class Foo {
    private int id;
    private string name;

    public Foo() : this(0, "") {
    }

    public Foo(int id) : this(id, "") {
    }

    public Foo(string name) : this(0, name) {
    }

    public Foo(int id, string name) {
        this.id = id;
        this.name = name;
    }
}