In .net, the value types are stored on stack where as reference types are stored on managed heap. What is the reason for this one? Is it not possible to exchange their storage locations?
-
5"the value types are stored on stack where as reference types are stored on managed heap." This is a huge fallacy - value types are equally able to be stored in the heap (via boxing or embedded in a reference type), or could be stored in a register. And what about references? (nether reference type nor value type)– MattDaveyMar 29, 2012 at 9:47
2 Answers
The stack is an implementation detail. The important thing is the reference/value distinction.
Is it not possible to exchange their storage locations?
It's very easy to store value types on the heap.
class ReferenceInt
{
public int Field;
}
ReferenceInt n = new ReferenceInt();
// n.Field is now stored on the heap.
-
@Dan.. in the above example
n.Field
is reference type right!! So it will store on heap, but in above statement you said that easy to store value types on heap... two types are storing in heap only. two solutions sounds like same... can you please explain.– YSMMar 29, 2012 at 3:45 -
5
-
But the n.Field value type would be embedded in the ReferenceInt type, which is stored in the heap. So n.Field would not be on the stack. Mar 29, 2012 at 9:49