C# constructor execution order
In C#, when you do
Class(Type param1, Type param2) : base(param1)
is the constructor of the class executed first, and then the superclass constructor is called or does it call the base constructor first?
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 (recurse all of this :)
- The constructor bodies in the chain in this class are executed (note that there can be more than one if they're chained with
Foo() : this(...)
etc
Note that in Java, the base class is initialized before variable initializers are run. If you ever port any code, this is an important difference to know about :)
I have a page with more details if you're interested.
It will call the base constructor first. Also keep in mind that if you don't put the :base(param1)
after your constructor, the base's empty constructor will be called.
The constructor of the baseclass is called first.
Not sure if this should be a comment/answer but for those who learn by example this fiddle illustrates the order as well: https://dotnetfiddle.net/kETPKP
using System;
// order is approximately
/*
1) most derived initializers first.
2) most base constructors first (or top-level in constructor-stack first.)
*/
public class Program
{
public static void Main()
{
var d = new D();
}
}
public class A
{
public readonly C ac = new C("A");
public A()
{
Console.WriteLine("A");
}
public A(string x) : this()
{
Console.WriteLine("A got " + x);
}
}
public class B : A
{
public readonly C bc = new C("B");
public B(): base()
{
Console.WriteLine("B");
}
public B(string x): base(x)
{
Console.WriteLine("B got " + x);
}
}
public class D : B
{
public readonly C dc = new C("D");
public D(): this("ha")
{
Console.WriteLine("D");
}
public D(string x) : base(x)
{
Console.WriteLine("D got " + x);
}
}
public class C
{
public C(string caller)
{
Console.WriteLine(caller + "'s C.");
}
}
Result:
D's C.
B's C.
A's C.
A
A got ha
B got ha
D got ha
D
Coincidentally , this is also a most asked interview question as well and its explained in this youtube video with demonstration.
First thing do not try to memorize the sequence. Think logically in parent child relationship , child builds on the top of the parent . So obviously first Parent instance should be created and then child.
So first the parent constructor fires and then child constructor.
But hang on there is a twist when it comes to initializers things are different.
For initializers first child initializers run and then parent initializers.
Below is the diagrammatic representation of the same. So constructor code fires Parent to Child and Initializers fire from Child to Parent.