How to do constructor chaining in C#

Alex picture Alex · Nov 29, 2009 · Viewed 146.7k times · Source

I know that this is supposedly a super simple question, but I've been struggling with the concept for some time now.

My question is, how do you chain constructors in C#?

I'm in my first OOP class, so I'm just learning. I don't understand how constructor chaining works or how to implement it or even why it's better than just doing constructors without chaining.

I would appreciate some examples with an explanation.

So how do how chain them?
I know with two it goes:

public SomeClass this: {0}

public SomeClass
{
    someVariable = 0
} 

But how do you do it with three, four and so on?

Again, I know this is a beginner question, but I'm struggling to understand this and I don't know why.

Answer

Marc Gravell picture Marc Gravell · Nov 29, 2009

You use standard syntax (using this like a method) to pick the overload, inside the class:

class Foo 
{
    private int id;
    private string name;

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

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

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

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

then:

Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");

Note also:

  • you can chain to constructors on the base-type using base(...)
  • you can put extra code into each constructor
  • the default (if you don't specify anything) is base()

For "why?":

  • code reduction (always a good thing)
  • necessary to call a non-default base-constructor, for example:

    SomeBaseType(int id) : base(id) {...}
    

Note that you can also use object initializers in a similar way, though (without needing to write anything):

SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
         z = new SomeType { DoB = DateTime.Today };