Possible Duplicate:
Fields of class, are they stored in the stack or heap?
If I have
Class A
{
int k=0;
}
and I'm doing:
A x = new A();
where is k
stored? On the heap or the stack? And why?
Possible Duplicate:
Fields of class, are they stored in the stack or heap?
If I have
Class A
{
int k=0;
}
and I'm doing:
A x = new A();
where is k
stored? On the heap or the stack? And why?
Even though k
is an int which is a value type it is contained in a reference type, so it will be stored on the heap as part of the memory allocated for x
- while this is an implementation detail, this is the current behavior of .NET.
It's (probably - see below) stored on the heap, along with all the rest of the class's data.
It's not stored on the stack because it doesn't really make any sense to put it there. Since the value is part of a reference type, it continues to live even after the current procedure exits. If it were on the stack, though, then it would be deleted after stack frame is popped. This would render the object invalid, unless there were some truly monumental extra work going on to try and shuffle it up and down the stack in order to keep it alive.
Furthermore, stack is a small space and sticking every instance of every value type ever created in the code would result in it running out of space very, very quickly.
However, the most correct answer is that the location where data is stored is an implementation detail, so you should assume you don't (and can't) know. The real distinction between reference and value types is the on that's built into their names: For value types, operations such as assignment and passing as arguments results in the object's value being copied. For reference types, such operations create an additional reference to the original object.