Where does the memory is allocated for static,constant and readonly fields?

Viewed 1094

I have used the three fields in the program and got the difference in usage but I am little confused where does these fields are getting stored? either in data segment(stack or heap?) or code segment?

static int a;
const int b=1235;
readonly int c;

in ILDASM the the fields are described as the following

for static: .field private static int32 a

for constant: .field private static literal int32 b = int32(0x000004D3)

for readonly: .field private initonly int32 c

3 Answers

Every 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. (There don't need to be any instances created for that one slot to exist though.) The details of exactly which heap the variables live on are complicated. more info you can find HERE

CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-time enviornment in the .NET Framework that runs the codes and helps in making the development process easier by providing the various services. The CLR divides the memory into three distinct regions: the stack, the heap, and the high frequency heap. Static objects need to survive a GC collection and are stored in the high frequency heap. Static and constants objects are stored in the loader heap as they exist in the memory throughout the lifetime of the application; they don't need to be garbage collected.

Related