When are value types stored in stack(C#)?

When I read next book of chapter "Value and reference types" then a question comes to my mind: "When are value types stored in stack"? Cause programmer cannot initialise any value type out of class. Cause when we initialise some variable of value type in class then variable is stored in heap.

My question is: when are value types stored in stack?


Well, firstly it is very rare that you would need to know, but basically, value-types are stored where-ever they are owned.

They are stored on the stack when they are part of the execution flow of a thread, which can mean:

  • in a "local" (a method variable) - excluding some cases (below)
  • as a floating value in part of a method, ie the return value from one method that is about to be passed as a value to another method - no "local" is involved, but the value is still on the stack
  • value-type parameters that are passed by-value (ie without ref or out ) are simply a special-case of this
  • in an instance "field" (a type variable) on another value-type that is itself on the stack (for the above reasons)
  • They are stored on the heap (as part of an object) when:

  • in an instance "field" on a class
  • in an instance "field" on a value-type that is itself on the heap
  • in a static "field"
  • in an array
  • in a "local" (a method variable) that is part of an iterator block, an async method, or which is a "captured" variable in a lambda or anonymous method (all of which cause the local to be hoisted onto a field on a class that is generated by the compiler)
  • when "boxed" - ie cast into a reference-type ( object , dynamic , Enum , ValueType (yes: ValueType is a reference-type; fun, eh?), ISomeInterface , etc)

  • My question is: when are value types stored in stack?

    From The Truth About Value Types:

    [I]in the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value


    The first web search hit on your question gives you Eric Lippert's The Truth About Value Types, which starts with the most important part: it is almost always irrelevant. So, why do you want to know? Will you program differently?

    Anyway:

    The truth is: the choice of allocation mechanism has to do only with the known required lifetime of the storage.

    链接地址: http://www.djcxy.com/p/78894.html

    上一篇: 如果一个数组被用作struct(C#)中的一个元素,它在哪里存储?

    下一篇: 值类型何时存储在堆栈(C#)中?