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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With