Click here to Skip to main content
15,903,385 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
what is Order Precedence of constructors c# in classes?
Posted

There is no real concept of order precedence in constructors. The constructor that gets called is the one that matches the signature of the calling code - now, you may get a point where a constructor delegates responsibility to another constructor (either through calling base(...) or this(....), but the one that is called is always the first that is hit - even though it might not be the code that first execute. Saying that, what actually happens when you do this is interesting. Consider this class structure:
C#
public class Program
{
    static void Main(string[] args)
    {
        Bar bar = new Bar();
        Bar bar2 = new Bar("FooBar");

        Console.ReadKey();
    }
}

public class Foo
{
    public Foo()
    {
        Console.WriteLine("Foo");
    }
}

public class Bar : Foo
{
    public Bar()
        : base()
    {
        Console.WriteLine("Bar");
    }

    public Bar(string text)
        : this()
    {
        Console.WriteLine(text);
    }
}
The line Bar bar = new Bar(); might make you think that the application will write out Bar and then Foo because the constructor in Bar is called first, but that's not what actually happens. Even though the Bar constructor is instantiated, the first thing it does is pass control to the base constructor via the base() operation. So, the constructor in Foo executes before the constructor in Bar does in this case. In Bar bar2 = new Bar("FooBar"); we see a similar issue because the constructor for Bar(string text) passes control to Bar() using this() before it can continue processing (in this case, the constructor for Bar passes control down to Foo before it executes. So for the first constructor, the following is output:
Foo
Bar
The second constructor call generates this:
Foo
Bar
FooBar
I hope this helps.
 
Share this answer
 
The order is:

Member variables are initialized to default values for all classes in the hierarchy
Then starting with the most derived class:

Variable initializers are executed for the most-derived type
Constructor chaining works out which base class constructor is going to be called
The base class is initialized 
The constructor bodies in the chain class are executed (note that there can be more than one if they're chained 


Regards,
Praveen Nelge
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900