How does .net managed memory handle value types inside objects?

前端 未结 6 1877
[愿得一人]
[愿得一人] 2021-01-18 21:42
public class MyClass
{
    public int Age;
    public int ID;
}

public void MyMethod() 
{
    MyClass m = new MyClass();
    int newID;
}

To my un

6条回答
  •  自闭症患者
    2021-01-18 21:52

    • Ans#1: Heap. Paraphrasing Don Box from his excellent 'Essential .Net Vol 1'

    Reference Types(RT) always yield instances that are allocated on the heap. In contrast, value types(VT) are dependent on the context - If a local var is a VT, the CLR allocates memory on the stack. If a field in a class is a member of a VT, then the CLR allocates memory for the instance as part of the layout of the object/Type in which field is declared.

    • Ans#2: No. Boxing would occur only when you access a struct via a Object Reference / Interface Pointer. obInstance.VT_typedfield will not box.

      RT variables contains the address of the object it refers to. 2 RT var can point to the same object. In contrast, VT variables are the instances themselves. 2 VT var cannot point to same object(struct)

    • Ans#3: Don Box's Essential .net / Jeffrey Richter's CLR via C#. I have a copy of the former... though the later may be more updated for .Net revisions

提交回复
热议问题