A static field in C# is a state variable declared with theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
static modifier that belongs to the type itself rather than to any specific object instance. Consequently, only a single copy of the field exists in memory, shared across all instances of the declaring type within the same Application Domain (AppDomain) or Assembly Load Context.
Syntax and Access
A static field is declared using thestatic keyword before the data type. It is accessed using the type name, not an instance reference. Attempting to access a static field through an object instance results in a compile-time error.
Memory Allocation and Lifecycle
- Allocation: Static fields are not stored with instance data on the standard managed heap. Instead, they are stored in a specialized memory region associated with the type object itself (historically referred to as the High-Frequency Heap).
- Initialization: The Common Language Runtime (CLR) guarantees that static fields are initialized exactly once. This initialization occurs before the first instance of the type is created or before any static member of the type is referenced. If not explicitly assigned, they default to the standard default value for their type (e.g.,
0forint,nullfor reference types). - Lifetime: The memory allocated for a static field persists for the entire lifetime of the AppDomain. It is not eligible for standard Garbage Collection (GC) until the AppDomain is unloaded.
Threading Implications
Because static fields represent globally shared state within an AppDomain, they are not inherently thread-safe. If multiple threads perform concurrent read and write operations on a static field, it will result in race conditions. To ensure thread safety, developers must implement explicit synchronization mechanisms:Modifier Combinations
Static fields are frequently combined with other modifiers to alter their mutability or threading behavior:static readonly: The field can only be assigned a value at the point of declaration or within a static constructor. Once the static constructor finishes execution, the reference or value becomes immutable.[ThreadStatic]Attribute: Applying this attribute to a static field alters the CLR’s allocation behavior. Instead of one field per AppDomain, the CLR provisions a unique, isolated copy of the static field for every thread that accesses it.
Master C# with Deep Grasping Methodology!Learn More





