ECMA-334 C# Language Specification17.11: Static constructors |
A static constructor is a member that implements the actions required to initialize a class. Static constructors are declared using static-constructor-declarations:
attributes
opt static-constructor-modifiers
identifier
(
)
static-constructor-body
block
;
A static-constructor-declaration
may include a set of attributes (24) and an extern modifier (17.5.7).
The identifier of a static-constructor-declaration
must name the class in which the static constructor is declared. If any other name is specified, a compile-time error occurs.
When a static constructor declaration includes an extern modifier, the static constructor is said to be an external static constructor. Because an external static constructor declaration provides no actual implementation, its static-constructor-body
consists of a semicolon. For all other static constructor declarations, the static-constructor-body
consists of a block, which specifies the statements to execute in order to initialize the class. This corresponds exactly to the method-body
of a static method with a void return type (17.5.8).
Static constructors are not inherited, and cannot be called directly.
The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
If a class contains the Main method (10.1) in which execution begins, the static constructor for that class executes before the Main method is called. If a class contains any static fields with initializers, those initializers are executed in textual order immediately prior to executing the static constructor.
must produce the output: using System;
class Test
{
static void Main() {
A.F();
B.F();
}
}
class A
{
static A() {
Console.WriteLine("Init A");
}
public static void F() {
Console.WriteLine("A.F");
}
}
class B
{
static B() {
Console.WriteLine("Init B");
}
public static void F() {
Console.WriteLine("B.F");
}
}
because the execution of A's static constructor is triggered by the call to A.F, and the execution of B's static constructor is triggered by the call to B.F. end example]Init A
A.F
Init B
B.F
It is possible to construct circular dependencies that allow static fields with variable initializers to be observed in their default value state.
produces the output using System;
class A
{
public static int X;
static A() { X = B.Y + 1;}
}
class B
{
public static int Y = A.X + 1;
static B() {}
static void Main() {
Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y);
}
}
X = 1, Y = 2