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
To be precise, the stack and the heap are (or should be) irrelevant in managed environments.
In practice, local variables value types (structs in C#) tend to be allocated on the stack. However, there are cases when they are allocated on the heap instead.
One such case is when they are boxed. Boxing means using an Int32
as an Object
, for example by passing it to a method that takes an object
parameter. One reason for this is polymorphism: Structs don't carry a vTable pointer and thus cannot do dynamic virtual method resolution (for such methods as ToString()
, for example) - but they are sealed, so they can do the resolution statically. On the other hand, if a struct is forced to be stored in an object
reference, it needs to be transformed to a heap-allocated vTable-enabled object.
A value type may also be allocated in the heap when it's part of a heap-allocated object - for example, when it's a data member (field) of a class.