Home > Backend Development > C++ > Is C#'s Static Class Initialization Order Guaranteed to Be Deterministic?

Is C#'s Static Class Initialization Order Guaranteed to Be Deterministic?

Barbara Streisand
Release: 2025-01-04 15:07:40
Original
570 people have browsed it

Is C#'s Static Class Initialization Order Guaranteed to Be Deterministic?

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:

  • If a static field initializer exists in a class, it is executed immediately before the class's static constructor.
  • If a static constructor exists in a class, its execution is triggered when any of the class's static members are referenced or when an instance of the class is created.
  • If a class contains the Main method, its static constructor is executed before Main is called.

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

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
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template