Home > Backend Development > C++ > Is C#'s Static Class Initialization Order Predictable?

Is C#'s Static Class Initialization Order Predictable?

DDD
Release: 2025-01-04 20:15:41
Original
861 people have browsed it

Is C#'s Static Class Initialization Order Predictable?

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:

  • Static field initializers are executed immediately prior to the static constructor.
  • Execution of a static constructor is triggered by the first use of a static field or when an instance of the class is created.
  • If the class contains Main(), its static constructor runs before Main() is called.

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);
    }
}
Copy after login

Execution Order

  1. A.X is used in Main(), triggering initialization of A().
  2. A().X initialization requires B.X, calling B().
  3. B().X is initialized to 7 (Console.WriteLine("B.X = 7")).
  4. B().X is modified and Console.WriteLine("B.X = 0") is executed.
  5. A().X is set to B.X 1 (Console.WriteLine("A.X = 1")).
  6. Console.WriteLine("A = 1, B = 0") is output.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template