How is memory allocated for a static variable?

43,423

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.

Share:
43,423
gk.
Author by

gk.

Updated on March 10, 2020

Comments

  • gk.
    gk. about 4 years

    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?

  • StayOnTarget
    StayOnTarget over 5 years
    This is a C# question
  • Masuri
    Masuri over 3 years
    Is it true that making static variable to null makes it's GC'ed. I'm really confused.