Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 915
SAIguru011 Avatar asked Jan 09 '19 07:01

SAIguru011


People also ask

Where are const variables stored memory?

As per the memory layout of C program ,constant variables are stored in the Initialized data segment of the RAM. But as per some of the Microcontroller memory layout ,const variables are stored in FLASH Memory.

Is constants are allocated memory?

Constants have no storage location at runtime. All access to constant identifiers results in the literal value of that constant replacing the identifier when the code is compiled.

What is difference between static constant and readonly variables in C#?

The first difference is the timeslot which initializes the const or readonly variables. The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level.

Where static memory is created?

The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).


1 Answers

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/

like image 145
Akarsha Rao Avatar answered Sep 23 '22 22:09

Akarsha Rao