<pre><code>public class MyClass
{
    public int Age;
    public int ID;
}

public void MyMethod() 
{
    MyClass m = new MyClass();
    int newID;
}
</code></pre>

<p>To my understanding, the following is true:</p>

<ol>
<li>The reference m lives on the stack and goes out of scope when MyMethod() exits.</li>
<li>The value type newID lives on the stack and goes out of scope when MyMethod() exits.</li>
<li>The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists. </li>
</ol>

<p>Here is my question:</p>

<ol>
<li>Do value types within objects live on the stack or the heap?</li>
<li>Is boxing/unboxing value types in an object a concern?</li>
<li>Are there any detailed, yet understandable, resources on this topic?</li>
</ol>

<p>Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there.</p>

<p>Edit:</p>

<p>Suggested reading for this topic:</p>

<ol>
<li><a href="http://www.microsoft.com/MSPress/books/6522.aspx" rel="nofollow noreferrer">CLR Via C# by Jeffrey Richter</a></li>
<li><a href="http://books.google.com/books?id=Kl1DVZ8wTqcC&amp;dq=essential+.net&amp;pg=PP1&amp;ots=5a-UEHSLVJ&amp;sig=D2_xn2kzMnP8zLXDVIV6AJtfbCY&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result#PPP1,M1" rel="nofollow noreferrer">Essential .NET by Don Box</a></li>
</ol>

[{'answer_id': 24832, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 2, 'selected': False, 'text': "<ol>\n<li>Any references or value types that an object own live in the heap.</li>\n<li>Only if you're casting ints to Objects.</li>\n</ol>\n"}, {'answer_id': 24846, 'author': 'Harpreet', 'author_id': 855, 'author_profile': 'https://Stackoverflow.com/users/855', 'pm_score': 2, 'selected': False, 'text': "<p>The best resource I've seen for this is the book CLR via C# by Jeffrey Richter.  It's well worth reading if you do any .NET development.  Based on that text, my understanding is that the value types within a reference type do live in the heap embedded in the parent object.  Reference types are <strong>always</strong> on the heap.\nBoxing and unboxing are not symmetric. Boxing can be a bigger concern than unboxing. Boxing <strong>will</strong> require copying the contents of the value type from the stack to the heap.  Depending on how frequently this happens to you there may be no point in having a struct instead of a class.  If you have some performance critical code and you're not sure if boxing and unboxing is happening use a tool to examine the IL code of your method.  You'll see the words box and unbox in the IL.  Personally, I would measure the performance of my code and only then see if this is a candidate for worry.  In your case I don't think this will be such a critical issue.  You are not going to have to copy from the stack to the heap (box) every time you access this value type inside the reference type.  That scenario is where boxing becomes a more meaningful problem.</p>\n"}, {'answer_id': 24871, 'author': 'Brad Wilson', 'author_id': 1554, 'author_profile': 'https://Stackoverflow.com/users/1554', 'pm_score': 1, 'selected': False, 'text': "<blockquote>\n  <p>Do value types within objects live on the stack or the heap?</p>\n</blockquote>\n\n<p>On the heap. They are part of the allocation of the footprint of the object, just like the pointers to hold references would be.</p>\n\n<blockquote>\n  <p>Is boxing/unboxing value types in an object a concern?</p>\n</blockquote>\n\n<p>There's no boxing here.</p>\n\n<blockquote>\n  <p>Are there any detailed, yet understandable, resources on this topic?</p>\n</blockquote>\n\n<p>+1 vote for Richter's book.</p>\n"}, {'answer_id': 24876, 'author': 'icelava', 'author_id': 2663, 'author_profile': 'https://Stackoverflow.com/users/2663', 'pm_score': 4, 'selected': True, 'text': '<p>Value-type values for a class <em>have</em> to live together with the object instance in the managed heap. The thread\'s stack for a method only lives for the duration of a method; how can the value persist if it only exists within that stack?</p>\n\n<p>A class\' object size in the managed heap is the sum of its value-type fields, reference-type pointers, and additional CLR overhead variables like the Sync block index. When one assigns a value to an object\'s value-type field, the CLR copies the value to the space allocated within the object for that particluar field.</p>\n\n<p>Take for example, a simple class with a single field.</p>\n\n<pre><code>public class EmbeddedValues\n{\n  public int NumberField;\n}\n</code></pre>\n\n<p>And with it, a simple testing class.</p>\n\n<pre><code>public class EmbeddedTest\n{\n  public void TestEmbeddedValues()\n  {\n    EmbeddedValues valueContainer = new EmbeddedValues();\n\n    valueContainer.NumberField = 20;\n    int publicField = valueContainer.NumberField;\n  }\n}\n</code></pre>\n\n<p>If you use the MSIL Disassembler provided by the .NET Framework SDK to peek at the IL code for EmbeddedTest.TestEmbeddedValues()</p>\n\n<pre><code>.method public hidebysig instance void  TestEmbeddedValues() cil managed\n{\n  // Code size       23 (0x17)\n  .maxstack  2\n  .locals init ([0] class soapextensions.EmbeddedValues valueContainer,\n           [1] int32 publicField)\n  IL_0000:  nop\n  IL_0001:  newobj     instance void soapextensions.EmbeddedValues::.ctor()\n  IL_0006:  stloc.0\n  IL_0007:  ldloc.0\n  IL_0008:  ldc.i4.s   20\n  IL_000a:  stfld      int32 soapextensions.EmbeddedValues::NumberField\n  IL_000f:  ldloc.0\n  IL_0010:  ldfld      int32 soapextensions.EmbeddedValues::NumberField\n  IL_0015:  stloc.1\n  IL_0016:  ret\n} // end of method EmbeddedTest::TestEmbeddedValues\n</code></pre>\n\n<p>Notice the CLR is being told to <strong>stfld</strong> the loaded value of "20" in the stack to the loaded EmbeddValues\' NumberField field location, directly into the managed heap. Similarly, when retrieving the value, it uses <strong>ldfld</strong> instruction to directly copy the value out of that managed heap location into the thread stack. No box/unboxing happens with these types of operations.</p>\n'}, {'answer_id': 24909, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 2, 'selected': False, 'text': "<ul>\n<li>Ans#1: Heap. Paraphrasing Don Box from his excellent 'Essential .Net Vol 1'</li>\n</ul>\n\n<blockquote>\n  <p>Reference Types(RT) always yield instances that are allocated on the heap. <strong>In contrast, value types(VT) are dependent on the context - If a local var is a VT, the CLR allocates memory on the stack. If a field in a class is a member of a VT, then the CLR allocates memory for the instance as part of the layout of the object/Type in which field is declared.</strong></p>\n</blockquote>\n\n<ul>\n<li><p>Ans#2: No. Boxing would occur only when you access a struct via a Object Reference / Interface Pointer. <em>obInstance.VT_typedfield</em> will not box.</p>\n\n<blockquote>\n  <p>RT variables contains the address of the object it refers to. 2 RT var can point to the same object. <strong>In contrast, VT variables are the instances themselves. 2 VT var cannot point to same object(struct)</strong></p>\n</blockquote></li>\n<li><p>Ans#3: Don Box's Essential .net / Jeffrey Richter's CLR via C#. I have a copy of the former... though the later may be more updated for .Net revisions</p></li>\n</ul>\n"}, {'answer_id': 21390848, 'author': 'supercat', 'author_id': 363751, 'author_profile': 'https://Stackoverflow.com/users/363751', 'pm_score': 0, 'selected': False, 'text': '<p>A variable or other storage location of a structure type is an aggregation of that type\'s public and private instance fields.  Given</p>\n\n<pre><code>struct Foo {public int x,y; int z;}\n</code></pre>\n\n<p>a declaration <code>Foo bar;</code> will cause <code>bar.x</code>, <code>bar.y</code>, and <code>bar.z</code> to be stored wherever <code>bar</code> is going to be stored.  Adding such a declaration of <code>bar</code> to a class will, from a storage-layout perspective, be equivalent to adding three <code>int</code> fields.  Indeed, if one never did anything with <code>bar</code> except access its fields, the fields of <code>bar</code> would behave the same as would three fields <code>bar_x</code>, <code>bar_y</code>, and <code>bar_cantaccessthis_z</code> [accessing the last one would require doing things with <code>bar</code> other than accessing its fields, but it would take up space whether or not it\'s ever actually used for anything].</p>\n\n<p>Recognizing structure-type storage locations as being aggregations of fields is the first step to understanding structures.  Trying to view them as holding some kind of object might seem "simpler", but doesn\'t match how they actually work.</p>\n'}]
['https://Stackoverflow.com/questions/24829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1880/']