
Deterministic Order of Static Class Initialization in C#
The order of static class initialization in C# is clarified by the ECMA specification. This order ensures consistency in program behavior.
According to ECMA-334:
- When a static field initializer exists, it executes immediately before the corresponding static constructor.
- If there's no static constructor, initializers execute at an implementation-dependent time before using any static field of the class.
- Execution of a static constructor triggers when either an instance of the class is created or any static member is referenced.
- In classes with a Main method, the static constructor executes before entering the Main method.
In the given code sample:
- Referencing A.X in Main triggers the initialization of A.X.
- A.X initialization requires B.X, so it initiates B.X initialization.
- B.X is assigned a default value of 7. Output: "B.X = 7."
- Static B() is called, outputting "B.X = 0."
- A.X is initialized as B.X 1, resulting in A.X = 1.
- Static A() is called, outputting "A.X = 1."
- Finally, Main prints "A = 1, B = 0."
The standard discourages observing static fields with variable initializers in their default state to maintain consistency.
The above is the detailed content of How Does C# Guarantee a Deterministic Order for Static Class Initialization?. For more information, please follow other related articles on the PHP Chinese website!