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
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.
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.
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.
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).
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With