Home > Backend Development > C++ > How are Static Variables Initialized in C#?

How are Static Variables Initialized in C#?

Barbara Streisand
Release: 2025-01-03 18:05:41
Original
671 people have browsed it

How are Static Variables Initialized in C#?

Initialization of Static Variables in C#

In C#, static variables are initialized differently depending on the presence of a static constructor and the beforefieldinit flag.

Initialization without a Static Constructor

If there is no static constructor defined within a class, static variables are initialized:

  • When the type is loaded into memory.
  • Before any instance constructors are called.
  • Eagerly, meaning the values are assigned immediately.

Initialization with a Static Constructor

When a static constructor is present:

  • beforefieldinit Flag:

    • false: Static variables are initialized before the static constructor is called.
    • true: Static variables are initialized lazily, when they are first accessed.
  • .NET 4 and Earlier: beforefieldinit defaults to false, resulting in eager initialization.
  • .NET 4.5 and Later: beforefieldinit defaults to true, leading to lazy initialization.

Conclusion

The initialization of static variables in C# depends on the presence of a static constructor and the value of the beforefieldinit flag. To ensure proper initialization, it is recommended to not rely on any specific behavior and simply use regular code to access static fields.

The above is the detailed content of How are Static Variables Initialized in C#?. 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