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?
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Child t = new Child();
}
}
class Parent
{
public Parent()
{
Console.WriteLine("Parent Instance Constructor");
Console.ReadKey();
}
static Parent()
{
Console.WriteLine("Parent Static Constructor");
Console.ReadKey();
}
}
class Child : Parent
{
public Child()
{
Console.WriteLine("Child Instance Constructor");
Console.ReadKey();
}
static Child()
{
Console.WriteLine("Child Static Constructor");
Console.ReadKey();
}
}
}
Output:
Child Static Constructor
Parent Static Constructor
Parent Instance Constructor
Child Instance Constructor
Now As per Jeppe Stig Nielsen Suggestion when i have intialised static fields in constructors,it is running in following order
Output
Parent Static Constructor
Child Static Constructor
Parent Instance Constructor
Child Instance Constructor
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");
}
}
why such contradictory behaviour?
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,
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