Search code examples
c#constructorconstructor-chaining

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?


Solution

  • 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.