Does structs have type objects created in heap? [duplicate]

随声附和 提交于 2021-02-17 07:22:22

问题


I am reading a book which shows how a class instance is created in heap as the picture below shows:

internal class Employee {
   public Int32 GetYearsEmployed() { ... }
   public virtual String GetProgressReport() { ... }
   public static Employee Lookup(String name) { ... }
}

internal sealed class Manager : Employee {
   public override String GetProgressReport() { ... }
}

and the author just focus on talking about those two class types, leaving out the details of value type Int32.

We can see that the class instance created in heap also holds a pointer to its type object which is an instance of System.Type

My understanding is , all of the structures are immediately derived from the System.ValueType abstract type. System.ValueType is itself immediately derived from the System.Object type. so structures derived from System.Object type just like classes.

So for the value type Int32 year, I know it is create on stack, but I think there is a also a type obect create in heap, so technially speaking, below statment is wrong if someone says:

when a struct instance is creatd, the instance create on stack( if the struct is not wrapped in class) , nothing happens in heap or nothing created in heap.

(Note that I know struct can be created on heap if they are boxed, or if they are fields in a class, or if they are elements of an array etc, but in my this simple case, it gets created on stack)

this part 2 of this statment is wrong as there is still a type object created on heap to link the struct instance on stack,

Q1-is my understanding correct?

Q2-if my understanding correct, that means the struct instance not only containing all its filed on stack, it must also hold a pointer that points to the type object, so that size of a struct instance is not as simple as the adding up all fields' size, there is extra overhead, a pointer, is my understanding correct?

P.S. some poeple quibble the context of the M3 method to show Int32 might not created on stack, here is the context:

class Program
{
    static void Main(string[] args) {
        M3();
    }
}

now Int32 year get stored on stack

来源:https://stackoverflow.com/questions/65929369/does-structs-have-type-objects-created-in-heap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!