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

后端 未结 5 1289
难免孤独
难免孤独 2021-01-15 04:23

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

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 05:24

    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.

提交回复
热议问题