Reputation: 17288
Are the value types defined inside a reference type stored on the heap or on the stack?
Upvotes: 7
Views: 3191
Reputation: 86718
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.
Upvotes: 5
Reputation: 11975
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".
Upvotes: 1