Friday, June 28, 2019

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?



Answer



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, i.e. 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 (i.e. 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" - i.e. cast into a reference-type (object, dynamic, Enum, ValueType (yes: ValueType is a reference-type; fun, eh?), ISomeInterface, etc)


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...