Is Static Class Initialization Order in C# Deterministic?
The order of static class initialization in C# is indeed deterministic. According to the ECMA-334 standard:
Initialization Order Example
Consider the following code:
static class B { public static int X = 7; static B() { Console.WriteLine("B.X = " + X); X = A.X; Console.WriteLine("B.X = " + X); } } static class A { public static int X = B.X + 1; static A() { Console.WriteLine("A.X = " + X); } } static class Program { static void Main() { Console.WriteLine("A = {0}, B = {1}", A.X, B.X); } }
Execution Order
Re-arrangement Considerations
Even if classes A and B are re-arranged, the order of initialization remains the same because the first use of A.X triggers the initialization chain.
Conclusion
The order of static class initialization is deterministic and follows the rules outlined in the ECMA-334 standard. The first use of a static member or the creation of an instance will trigger the initialization process, which proceeds in the order of field initializers followed by the static constructor.
The above is the detailed content of Is C#'s Static Class Initialization Order Predictable?. For more information, please follow other related articles on the PHP Chinese website!