How is the decimal value, whose size is 16 bytes, stored on the stack, where there are only 4 bytes in a 32-bit system? Where were my thoughts wrong?
Your opinion went wrong somewhere along the lines "32-bit link fits into 4 bytes" and ends with "the stack has a length of 4 bytes." The default stack is one million bytes; if the runtime decides to put the decimal variable (or value) on the stack, then it reserves 16 of these millions of bytes.
It's good that you think about how computers work under the hood, but of course, don't forget that the C # team worked hard to create a language in which you don't have to worry about whether the variables are on the stack or in the heap. You have to write very advanced programs to make a difference; I never wrote a C # program for business, where I needed to worry about the stack and heap, and I wrote programs in C # for more than 10 years.
UPDATE:
I updated the image to illustrate that I do not think the entire stack was 4 bytes long, but only one reference "memory box".
Good Excellent. So, let's assume that a link is four bytes, which on some machines it is. If the runtime is to push the link onto the stack, it reserves four bytes on the stack. There is no requirement that the stack be reserved in four-byte chunks. It can be reserved in pieces of any size.
So, I will clarify my explanation. You were mistaken when you suggested that βa link is four bytes, so the stack can only be reserved in four-byte chunks.β Any number of bytes can be reserved on the stack from zero to a million.
(Please donβt try to reserve a million, bad things will happen. There is a reason why the .NET guidelines say that you create 16 byte structures!)
Now, for performance reasons on some architectures, the runtime might try to reserve a stack stack so that each fragment is aligned with four-byte boundaries. Some equipment is really slow if the data is biased. But this is a level of detail that you hardly need to worry about in C #.
UPDATE again:
Here is another way to think about it. Suppose we have two normal local variables, which are 4-byte ints:
int x; int y;
This gets two pieces of memory, each four bytes. Now suppose we have a structure:
struct S { public int x; public int y; }
and we create a local variable:
S s;
This is exactly the same as before. We have two variables on the stack, and these variables are called sx and sy . Putting a structure on the stack is neither more nor less than putting all the variable fields that are in the structure on the stack.
GIVE ANOTHER UPDATE:
Another thing that may confuse you is that there is another kind of temporary storage called βregistersβ, which is also used to store local variables, and the registers really only have four bytes. (Except for those that are 8, but not there.) How is a 16-byte structure stored in a register? This is not . Runtime simply does not put large structures in registers.