As I know Constructors of parent class is called first and then child Class.But why In Case of static Constructor It executes from derived Class first and then Child Class?
First off, the behaviour is not contradictory at all; it is all consistent with the rules. You just don't know what the rules are.
You should read all of my two-part series on instance constructors and my four-part series on the semantics of static constructors. They start here:
http://blogs.msdn.com/b/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx
and here:
http://ericlippert.com/2013/02/06/static-constructors-part-one/
respectively.
Those should clearly answer your question, but in case it is not 100% clear let me sum up. The relevant rules are:
So what happens when you execute new Child()
?
So there you go; the order is the Child static constructor, then the Parent static constructor, then the Parent body, then the Child body.
Now let's look at your second example. What happens when you say new XyzChild
?
So there you go. There's no inconsistency whatsoever; the two rules are applied correctly.
Static
Constructors are always executed before the non-static constructor. Static constructor is called when class is accessed first time.
From MSDN Doc,
The order in which the static constructors are run is undefined (I think) in your case. The only thing that is guaranteed, is that they will run before instances are created.
I changed you code into:
class XyzParent
{
protected static int FieldOne;
protected int FieldTwo;
static XyzParent()
{
FieldOne = 1;
Console.WriteLine("parent static");
}
internal XyzParent()
{
FieldOne = 10;
FieldTwo = 20;
Console.WriteLine("parent instance");
}
}
class XyzChild : XyzParent
{
static XyzChild()
{
FieldOne = 100;
Console.WriteLine("child static");
}
internal XyzChild()
{
FieldOne = 1000;
FieldTwo = 2000;
Console.WriteLine("child instance");
}
}
Now it matters more which order they run in, for they write to the same field. And with my version of the code, saying new XyzChild();
leads to this output:
parent static
child static
parent instance
child instance
EDIT: Eric Lippert's answer gives a more precise explanation. The above code only does WriteLine
at the end of the static constructors. Add additional WriteLine
at the beginning of the static constructors to see that the XyzParent
static constructor is run "in the middle" of the execution of the XyzChild
static constructor.