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:
ref
or out
) are simply a special-case of this They are stored on the heap (as part of an object) when:
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#)中?