7

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?
2
  • 1
    I'd advise picking up either CLR via C# or C# in depth and going through the relevant chapters. It's not a trivial topic.. Commented Jun 10, 2010 at 5:13
  • Also possible dupe of stackoverflow.com/questions/1130468 Commented Jun 10, 2010 at 5:21

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Memory in .NET - what goes where by Jon Skeet

2 Comments

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

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".

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.