title: Stack and Heap memory allocation in .net
body: <p>I've been reading different articles/pages on this topic and finally came to <a href="http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx" rel="nofollow noreferrer">this article</a>, which led me to a confusion!</p>
  
  <p>In the article, it's mentioned that <code>Value Types always go where they were declared</code>, by which the author meant, value types may reside in either the stack or the heap, as per how/where they're declared.</p>
  
  <p>Let me put down a code snippet to make myself more clear:</p>
  
  <pre><code>public class Test
  {
      int testInt;
      string testString;
  }
  
  int anInt;
  string aString;
  Test testObj;
  testObj = new Test();
  </code></pre>
  
  <p>After executing these lines of code, the memory allocation will look something like this:</p>
  
  <p><img src="https://i.stack.imgur.com/GYVT1.jpg" alt="enter image description here"></p>
  
  <p>The struct <code>testInt</code> is stored in the heap, since it was declared in the <code>Test</code> class.</p>
  
  <p>Keeping this example in mind, let us see a simple Form.cs code behind where I'm declaring an integer.</p>
  
  <pre><code>using System.Windows.Forms;
  
  namespace WindowsFormsApplication1
  {
      public partial class Form1 : Form
      {
          public Form1()
          {
              InitializeComponent();
          }
  
          public int anotherInt;
      }
  }
  </code></pre>
  
  <p><strong>My confusion part:</strong></p>
  
  <p>In this case, where is <code>anotherInt</code> allocated to? Stack or Heap? By the looks of it, I think most of the answers will be "Stack". But, isn't this variable declared in a class called <code>Form1</code>? So, as per the first code snippet above, shouldn't it be going to the heap? If yes, then under what all circumstances would a struct be allocated to a Stack? Only if it is declared inside a method? But still, won't a method come under a class, which again should be stored in a heap?</p>
  
  <p>A lot of questions I know! But just curious to know what's happening. I hope my question is clear.</p>