Friday, November 11, 2005 12:16 PM
imranko
Where are value types and reference types allocated in memory?
Seems that a lot of people (including me) get this wrong the first time
around. In several books/on-line resources, you'll see the standard
explanation saying that value types are allocated on the stack while
reference types are allocated on the GC heap. For instance -
this article
does the same. This means people reading these online resources tend to
assume that the information is correct and move on ending up with a
wrong concept in their head (Trust me - I've been there :( ). Like
this
for example. Turns out - that piece of information isn't entirely
correct. Instead of re-writing stuff that others have already explained
really well, I'll just point you to the relevant resources. Suffice to
say that value types are NOT ALWAYS allocated on the stack.
Read this for a very nice explanation on where value types/reference types are allocated under various circumstances:
http://www.yoda.arachsys.com/csharp/memory.html
This is a more in-depth look at how the CLR creates objects and what objects go where in memory:
http://msdn.microsoft.com/msdnmag/issues/05/05/JITCompiler/
(take a look at the 'Type fundamentals' and 'ObjectInstance' sections for stuff relevant to this post).