开发者

Where are value types defined in a reference type stored (heap or stack)?

开发者 https://www.devze.com 2023-01-03 03:38 出处:网络
Are the value types defined inside a reference type stored on the heap or on the stack? If stored on the heap, then when are value types stored on the stack?

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 s开发者_开发问答tack, then what goes inside the heap as everything ends at a value type in the end?


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.


Memory in .NET - what goes where by Jon Skeet


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号