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?