Where are static members stored in memory? stack/

2019-09-22 07:59发布

问题:

This question already has an answer here:

  • Fields of class, are they stored in the stack or heap? 3 answers

The earlier post dealt with the value and reference types and their memory allocation.

Here I'm trying to understand the memory allocation of static members.

I have a simple class which has got both static and non-static integers like one shown below.

 class Sample
 {
   public int nonStaticInt = 0;
   public  static int staticInt = 0;
 }

My question here is, where do static integer reside? Stack/ a Heap. And how do they get into memory first even before any object creation.

Thanks!

回答1:

When a static variable is allocated, it will be stored as part of Methodtable. Methodtable means When a class is loaded first time in application, separate memory will be allocated in appdomain for class level variables and methods inside class. .

If static variable is primitive type, it will be stored as part of Methodtable. If it is reference type, it will be stored inside the heap and the reference will be stored in Methodtable