Static Variable Initialization in C#
When working with static variables in C#, it's crucial to understand the timing of their initialization.
Timing of Static Variable Initialization
Static variables are initialized when:
-
Static constructor is present: If a class has a static constructor (static MyStaticConstructor()), static variables are initialized when the static constructor is called for the first time.
-
No static constructor: If there is no static constructor, static variables are initialized when the type is loaded into memory.
Type Loading Trigger
Class loading is triggered by:
- Creating an instance of the class
- Accessing a static member of the class
- The class being explicitly loaded using reflection
Additional Considerations
- In .NET 4, static variable initialization became more "lazy," meaning they are initialized only when first accessed.
- If the beforefieldinit flag is set, static variables are initialized before any instance constructor is called. This flag is set by the presence of a static constructor.
- To ensure consistent behavior, it's recommended to avoid relying on specific initialization timing and simply initialize static variables through regular code access.
For further details and a comprehensive explanation, refer to Jon Skeet's article linked in the original response.
The above is the detailed content of When Are Static Variables Initialized in C#?. For more information, please follow other related articles on the PHP Chinese website!