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

5

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

c#
static
constants
readonly
asked on Stack Overflow Jan 9, 2019 by SAIguru011

3 Answers

3

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

answered on Stack Overflow Jan 9, 2019 by Leon Barkan
3

As you know const is static which means it is stored in the heap. Readonly is just like a member. Just like any other member the value of the readonly also gets stored on the heap. For any furthur reference about const and readonly refer the link below. https://blogs.msdn.microsoft.com/csharpfaq/2004/12/03/what-is-the-difference-between-const-and-static-readonly/

answered on Stack Overflow Jan 10, 2019 by Akarsha Rao
1

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.

answered on Stack Overflow Nov 20, 2019 by fasak123

User contributions licensed under CC BY-SA 3.0