Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor chaining precedence

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?

like image 809
Cole Tobin Avatar asked Nov 28 '25 02:11

Cole Tobin


2 Answers

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.

like image 99
Tudor Avatar answered Nov 30 '25 16:11

Tudor


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.

like image 30
S. Ravi Kiran Avatar answered Nov 30 '25 15:11

S. Ravi Kiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!