views:

72

answers:

3

Are the value types defined inside a reference type stored on the heap or on the stack?

  1. If stored on the heap, then when are value types stored on the stack?
  2. If stored on the stack, then what goes inside the heap as everything ends at a value type in the end?
+1  A: 

Memory in .NET - what goes where by Jon Skeet

bniwredyc
This doesn't actually answer his question (directly, anyway).
Adam Robinson
@Adam Robinson - you're right, thank you. I need to read questions more carefully.
bniwredyc
+1  A: 

As quoted from here:

Each local variable (ie one declared in a method) is stored on the stack. That includes reference type variables - the variable itself is on the stack, but remember that the value of a reference type variable is only a reference (or null), not the object itself. Method parameters count as local variables too, but if they are declared with the ref modifier, they don't get their own slot, but share a slot with the variable used in the calling code

I guess something like TextBox txtbx = new TextBox(); means that variable txtbx lives on the stack but its value is usually a reference to an object living on the heap.

Instance variables for a reference type are always on the heap. That's where the object itself "lives".

deostroll
only nw realized that two answers to this post as of this moment are pointing to the same article. :|
deostroll
+1, though your last sentence (the part that actually addresses the question) should probably come *first*
Adam Robinson
+1  A: 

The only variables stored on the stack are local variables for a function. For reference types, the reference is stored on the stack while the object it refers to is stored on the heap. For value types, the object itself is stored on the stack. Note that local variables that can escape from the local function (such as via a closure) are stored in a separate data structure on the heap, including any value types that may be included.

In other words, since reference types are always stored on the heap, anything they contain (even value types) is also stored on the heap.

Gabe