Home > Backend Development > C++ > Is C# Static Class Initialization Order Deterministic and Predictable?

Is C# Static Class Initialization Order Deterministic and Predictable?

Patricia Arquette
Release: 2025-01-04 00:43:09
Original
383 people have browsed it

Is C# Static Class Initialization Order Deterministic and Predictable?

Is Static Class Initialization Order in C# Predictable?

In C#, static class members are initialized in a deterministic order. This behavior is crucial to understand, as it can affect the outcome of your code, especially in situations involving circular dependencies between static members.

Initialization Sequence

According to the C# language specification (ECMA-334), the order of static class initialization is as follows:

  1. Execution of static field initializers (in textual order)
  2. Execution of the static constructor

This sequence ensures that all static fields are initialized before the static constructor is invoked.

Example

Consider the following code:

static class B
{
    public static int X = 7;
    static B() { ... }
}

static class A
{
    public static int X = B.X + 1;
    static A() { ... }
}

static class Program
{
    static void Main() { ... }
}
Copy after login

In this example, the initialization sequence is as follows:

  1. B.X is initialized to 7.
  2. A.X is initialized to B.X 1, which results in a default value since B.X has not yet been initialized.
  3. The static constructor of class B is invoked, and B.X is set to A.X, which is still the default value.
  4. The static constructor of class A is invoked, and A.X is set to B.X 1, which is now 1.

Therefore, the final values of A.X and B.X will be 1 and 0, respectively.

Implications

This predictable initialization order has important implications for coding practices. For instance, it emphasizes the importance of initializing static fields with explicit values, avoiding reliance on default values. Additionally, it ensures that static constructors are only executed once per class, even in scenarios with multiple references or instances.

By understanding this deterministic order, developers can write code that initializes and interacts with static members safely and efficiently.

The above is the detailed content of Is C# Static Class Initialization Order Deterministic and 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template