Where are static members stored in memory? stack/

2019-09-22 08:21发布

This question already has an answer here:

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条回答
女痞
2楼-- · 2019-09-22 08:37

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

查看更多
登录 后发表回答