Home >Backend Development >C++ >When Are C# Static Variables Initialized?
The Initialization Timing of Static Variables in C#
Static variables in C# are a powerful tool for sharing data across instances of a class. However, the timing of their initialization can be a bit confusing.
When Does Initialization Occur?
The initialization of static variables depends on the presence of a static constructor in the class. If a static constructor is present, static variables are initialized when the static constructor is called. If there is no static constructor, static variables are initialized lazily when they are first referenced.
When Does Class Loading Occur?
Class loading occurs when a reference to a type is encountered for the first time, either explicitly through the new operator or implicitly through reflection. Once a class is loaded, its static members, including static variables, are initialized.
Behavior Changes in .NET 4
In .NET 4, the initialization behavior of static variables changed to become more "lazy." In previous versions, static variables were always initialized when the class was loaded. In .NET 4, however, static variables are only initialized when they are first referenced. This change was made to improve performance in scenarios where static variables are not actually used.
Best Practices
While the initialization timing of static variables can be complex, it is important to remember that static fields will be initialized before they are used. As such, it is generally not advisable to rely on specific initialization timing when coding. For more detailed information and examples, it is recommended to refer to the resources provided by Jon Skeet in the original question's answer.
The above is the detailed content of When Are C# Static Variables Initialized?. For more information, please follow other related articles on the PHP Chinese website!