How is memory allocated for a static variable?

C#.NetMemory Management

C# Problem Overview


In the below program:

class Main
{   
    static string staticVariable = "Static Variable";
    string instanceVariable = "Instance Variable";

    public Main(){}   
}

The instanceVariable will be stored inside the memory allocated for object instance. Where will the staticVariable be stored, is it stored in the object instance itself or somewhere else? If its stored somewhere else, how are the memory locations connected?

C# Solutions


Solution 1 - C#

Memory for static variables are normally held in some rooted (and hidden) object[]. This can be seen doing a !gcroot on the object in WinDbg (with SOS).

Just to add, these references can never be GC'ed (unless you null the field), as I discovered recently.

Solution 2 - C#

For instance in C++ staic variables are allocated in global memory space with global variables. Compiler uses special naming convention to know that this variable belongs to the class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiongk.View Question on Stackoverflow
Solution 1 - C#leppieView Answer on Stackoverflow
Solution 2 - C#Nick BorodulinView Answer on Stackoverflow