I've been reading different articles/pages on this topic and finally came to this article, which led me to a confusion!
In the article, it's mentioned that Value Types always go where they were declared
, by which the author meant, value types may reside in either the stack or the heap, as per how/where they're declared.
Let me put down a code snippet to make myself more clear:
public class Test
{
int testInt;
string testString;
}
int anInt;
string aString;
Test testObj;
testObj = new Test();
After executing these lines of code, the memory allocation will look something like this:
The struct testInt
is stored in the heap, since it was declared in the Test
class.
Keeping this example in mind, let us see a simple Form.cs code behind where I'm declaring an integer.
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int anotherInt;
}
}
My confusion part:
In this case, where is anotherInt
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 Form1
? 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?
A lot of questions I know! But just curious to know what's happening. I hope my question is clear.
Best Answer
In your example
anotherInt
would be allocated to the Heap. This is becauseanotherInt
is a field ofForm1
, which is a Heap allocated object. The Stack is associated with a thread & contains only the references/objects necessary for the currently executing code. So to answer your question about methods coming under a class, you're not entierly correct there.While methods belong to a class, they are executable blocks of code rather than memory blocks associated directly with a class(which is what
anotherInt
is). One of the best ways to examine this type of allocation is to use a memory debugger like WinDbg & actually examine your thread stacks vs. the Heap. This will give you the clearest picture of where a particular struct is actually allocated.In an extremely simplified sense: Stack = addresses necessary for currently executing code stack, Heap = everything else. But ultimatley Jon B is spot on w/ his link to Eric's blog. You really don't need to know where your objects are allocated.
EDIT: Including the blog link.