C# static constructor ordering [closed]
I开发者_如何学编程 am curious as to the order that static and instance constructors are fired. Could someone help me by letting me know what order the constructors below fire?
And what is the explanation behind this behaviour for the execution order of the static constuctors?
class A
{
static A()
{
Console.WriteLine("I am in A's Static Constructor");
}
A()
{
Console.WriteLine("I am in A's Default Constructor");
}
}
class B:A
{
static B()
{
Console.WriteLine("I am in B's Static Constructor");
}
B()
{
Console.WriteLine("I am in B's Default Constructor");
}
}
class C:B
{
static C()
{
Console.WriteLine("I am in C's Static Constructor");
}
C()
{
Console.WriteLine("I am in C's Default Constructor");
}
}
What will be the output of the following statement:
C c = new C();
The order is: C, B, A static ctors. A, B, C, default ctors:
Update: Also see this great blog post (Part1 and Part2) from Eric Lippert on why static class initializers run in the reverse order than ctors.
I am in C's Static Constructor
I am in B's Static Constructor
I am in A's Static Constructor
I am in A's Default Constructor
I am in B's Default Constructor
I am in C's Default Constructor
精彩评论