Memory allocation in a program: Code and data. Stack. Heap.
If I have a static/global variable (lets say a primitive type), then theory suggests that memory is allocated when the compiled program is loaded (ignoring dynamic linking and loading in this example and assuming the program consists of one module).
But what if the global variable is a reference type? Does the runtime adjust the memory allocation of the code/data area? Or does the reference merely exist in the code/data area and points to a memory area in the heap?
Static variables are allocated from the AppDomain’s loader heap by the JIT compiler when it converts the IL to machine code. It directly compiles the address into the code, very efficient. It stays there until the heap is destroyed when the AppDomain gets unloaded. This is not a GC heap, the variable address never changes.
If it is a variable of a reference type then some code you wrote will run later to initialize the variable. Which stores the address of a chunk of memory from the garbage collected heap into the variable. It is then treated just like any other reference by the garbage collector, updating the value when the heap is compacted. And of course a very high likelihood that the referenced object will end up in generation 2 if you don’t explicitly assign a null to the variable.