Constructor chaining precedence

1k views Asked by At

Say I have this class:

class FooBar
{
    public FooBar() : this(0x666f6f, 0x626172)
    {
    }

    public FooBar(int foo, int bar)
    {
        ...
    }
 ...
}

If I did this:

FooBar foobar = new FooBar();

would the non-parameterized constructor execute first, then the parameterized one, or is it the other way around?

4

There are 4 answers

1
Tudor On BEST ANSWER

MSDN has a similar example with base:

public class Manager : Employee
{
    public Manager(int annualSalary)
        : base(annualSalary)
    {
        //Add further instructions here.
    }
}

And states:

In this example, the constructor for the base class is called before the block for the constructor is executed.

Nevertheless, to be sure here's my test:

class Program
{
    public Program() : this(0)
    {
        Console.WriteLine("first");
    }

    public Program(int i)
    {
        Console.WriteLine("second");
    }

    static void Main(string[] args)
    {
        Program p = new Program();
    }
}

Prints

second
first

so the parameterized constructor executes before the explicitly invoked one.

1
S. Ravi Kiran On

The control will reach the default constructor first. As we have a call to the parameterized constructor from there, execution of the statements in the default constructor will halted and the control will move to the parameterized constructor. Once the execution of statements in parameterized constructor is completed, the control will move back to the default constructor.

You may verify it by placing a break point at the default constructor.

0
Ruben On

Don't know if that is documented as "defined behavior", but TestClass(int) executes first and then TestClass().

0
Kamran On

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