Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

c# - How many type objects created in heap for a struct instance?

We know that for classes, for example, public class Employee {}, when we create an instance of it, there will be an Employee object created in heap, and CLR created a Type object (an instance of System.Type) in advance, so that Employee object holds a pointer that points to the type object. Since all type inherits from System.Object, a type object for System.Object was also created by CLR in advance.

Now let's say we change the class to struct as public struct Employee {} and when we create an instance of it as a local varable in Program's Main method, how many type objects will be created on heap? My assumption is three, one for the struct itself, the other one is a type object for System.ValueType since all structs inherit from System.ValueType, and since System.ValueType also inherits from System.Object, so the third type object is created by CLR for System.Object, is my understanding correct?

question from:https://stackoverflow.com/questions/65931999/how-many-type-objects-created-in-heap-for-a-struct-instance

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

System.Type, is memoised, there isn't a System.Type instance created everytime you instance an object of any given type, that would be extremely wasteful. You can check this out simply doing:

var type1 = (new Foo()).GetType();
var type2 = (new Foo()).GetType();
var areSame = ReferenceEquals(type1, type2); //returns true

As to when, how and in what order these memoised type instances are created, is not something I'd normally need to know the details about. To be frank, I find it hard to come up with a scenario where this knowledge would be useful. Care to further detail why you would need to know the exact mechanism?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...