Home > Backend Development > C++ > How Does C# Guarantee a Deterministic Order for Static Class Initialization?

How Does C# Guarantee a Deterministic Order for Static Class Initialization?

Mary-Kate Olsen
Release: 2025-01-03 17:19:42
Original
707 people have browsed it

How Does C# Guarantee a Deterministic Order for Static Class Initialization?

Deterministic Order of Static Class Initialization in C#

The order of static class initialization in C# is clarified by the ECMA specification. This order ensures consistency in program behavior.

According to ECMA-334:

  • When a static field initializer exists, it executes immediately before the corresponding static constructor.
  • If there's no static constructor, initializers execute at an implementation-dependent time before using any static field of the class.
  • Execution of a static constructor triggers when either an instance of the class is created or any static member is referenced.
  • In classes with a Main method, the static constructor executes before entering the Main method.

In the given code sample:

  1. Referencing A.X in Main triggers the initialization of A.X.
  2. A.X initialization requires B.X, so it initiates B.X initialization.
  3. B.X is assigned a default value of 7. Output: "B.X = 7."
  4. Static B() is called, outputting "B.X = 0."
  5. A.X is initialized as B.X 1, resulting in A.X = 1.
  6. Static A() is called, outputting "A.X = 1."
  7. Finally, Main prints "A = 1, B = 0."

The standard discourages observing static fields with variable initializers in their default state to maintain consistency.

The above is the detailed content of How Does C# Guarantee a Deterministic Order for Static Class Initialization?. For more information, please follow other related articles on the PHP Chinese website!

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