In .Net does const and static readonly are part of the containing class in regard the memory allocations? are they allocated per instance (even when they belong to the type itself)?
edit: how this works with Serializion and sizeof operation?
In .Net does const and static readonly are part of the containing class in regard the memory allocations? are they allocated per instance (even when they belong to the type itself)?
edit: how this works with Serializion and sizeof operation?
Memory for static
fields, constant or not, is never allocated per instance. Moreover, static const
is not allowed - const
is automatically considered one-per-class.
There are differences between const
and static readonly
fields, but neither one of them changes the footprint of instances of the corresponding class.
Memory for static
members are allocated once when the type is loaded since it belongs to the type itself.
As for const
it won't consume memory, they don't exist at all in runtime, they are burnt into IL. In other words they are hardcoded.
static
members of a class belong to the Type
, not the instance. The Type
itself is loaded in the Loader Heaps
, specifically inside the HighFrequencyHeap
once the type gets loaded. So to your question: No, they are not allocated per instance of the Class
.
Static variables are stored in the loader heap, where the type information is stored as types are loaded. This means that the storage for static variables will not be allocated until their type is loaded.