views:

5216

answers:

3

In the below program

Class Main{

static string staticVariable = "Static Variable";
string instanceVariable = "Instance Variable";

public Main(){}

}

The instanceVariable will be stored insided the memory allocated for object instance. Where will the static variable go, Is it stored in the object instance itself or some where else? If its stored some where else, how are the memory locations connected?

+2  A: 

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.

leppie
+13  A: 

Static variable is stored on the heap, regardless of whether it's declared within a reference type or a value type. There is only one slot in total no matter how many instances are created.

This heap is separate from the normal garbage collected heap - it's known as a "high frequency heap", and there's one per application domain.

You will find the below resource useful Static variable demystified

rajesh pillai
Nice extra info +1 :)
leppie
Glad you liked it.
rajesh pillai
@rajesh pillai: Does your answer hold good for `C++` also?
Lazer
A: 

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.

Nikita Borodulin