0

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?

Lior
  • 171
  • 2
  • 11
  • 1
    possible duplicate of [How's memory allocated for a static variable?](http://stackoverflow.com/questions/337019/hows-memory-allocated-for-a-static-variable) – Rik May 26 '14 at 12:19

4 Answers4

4

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.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

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.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
0

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.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
0

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.

Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70