Is Static Class Initialization Order in C# Deterministic?
In C#, static classes are initialized when they are first used. However, the sequence of initialization among multiple static classes is not always evident. This article explores the deterministic nature of static class initialization in C# and how it affects the execution of code.
Deterministic Initialization Order
The order of static class initialization is governed by the following rules:
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); } }
This code illustrates the deterministic nature of static class initialization. When A.X is referenced in Main, its static constructor is executed. A.X is initialized by using B.X, which triggers the initialization of B. Thus, the output of the code will always be:
A.X = 1 B.X = 7 B.X = 0 A = 1, B = 0
Conclusion
Static class initialization in C# follows a well-defined order. Understanding this order is crucial for writing code that behaves as intended. By adhering to the rules outlined above, developers can ensure that their static classes are initialized correctly and consistently, even across multiple compilations and executions.
The above is the detailed content of Is C#'s Static Class Initialization Order Guaranteed to Be Deterministic?. For more information, please follow other related articles on the PHP Chinese website!