The order by which constructors are called has nothing to do with constructors being default or non-default (parametrized), but rather it is determined by chaining relation.
In detail, every constructor which is followed by a this
keyword, is halted and program jumps to the constructor pointed to by this
keyword. When the last chained constructor is reached, its code is run. Then the program runs the previous constructor in the chain and this will go all the way back to the first one.
An example would clarify this.
Suppose inside a class you have 3 constructors as below:
public class Test
{
// ctor #1
public Test() : this(5) // this jumps to the ctor #2
{
Console.WriteLine("no params");
}
// ctor #2
public Test(int i) : this("Hi") // this jumps to the ctor #3
{
Console.WriteLine("integer=" + i.ToString());
}
// ctor #3
public Test(string str) // this ctor will be run first
{
Console.WriteLine("string=" + str);
}
}
If you call the default constructor with var t = new Test()
, you will see the following output:
// string=Hi -> ctor #3
// integer=5 -> ctor #2
// no params -> ctor #1