What is Type Object in Heap

2019-02-14 02:55发布

问题:

I know that when objects are created in Heap, they also have extra two more fields:

  1. Sync Block Index
  2. Type Object Pointer

So I wonder when Type Object is created in Heap memory and what kind of data it holds? It only represents the metadata of the Type?

I haven't been able to find much detail about that.

回答1:

The Type object also contains the bytes that back any static fields on the type as well as a method table with one entry per method defined within the type.

Each entry in the method table points to JIT-compiled native code if the method has been executed at least once.

The type object is created the first time the type is instantiated or the first time a static type member is referenced.

I highly recommend buying a copy of Jeffrey Richter's book, CLR via C# if you want to get a really deep understanding of what the CLR does. The section titled "How Things Relate at Runtime" in chapter 4 covers the .NET type allocation process on the heap in detail.

The May 2005 edition of MSDN magazine has an article titled "JIT and Run: Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects" with some good information as well, specifically the sections on Type Fundamentals and MethodTable.



回答2:

All the cast exceptions, type match and mismatch are done and handled by the CLR with the help of Type Object in .Net. Simplest and fastest way to create a type's Type Object is via typeof operator as shown below:

    var fileTypeObjectInHeap = typeof(File);

If you have ever done something like this in C# - comparing the type of an object o with some known type (here FileInfo):

var fileName = @"C:\sample.txt";
object o = new FileInfo(fileName);
if (o.GetType() == typeof(FileInfo)) { ... }

then you have used Type Object of that type unknowingly.

Corresponding to every type being used by your application (AppDomain to be precise) there is single instance of Type Object in heap which is referred for all such purposes. For more details and internals - quoting Jeffrey Richter from CLR via C# Fourth edition:

a Type object represents a type reference that is a lightweight object. If you want to learn more about the type itself, then you must acquire a TypeInfo object, which represents a type definition. You can convert a Type object to a TypeInfo object by calling System.Reflection.IntrospectionExtensions’ GetTypeInfo extension method.

Type typeReference = ...; // For example: o.GetType() or typeof(Object) 
TypeInfo typeDefinition = typeReference.GetTypeInfo();


标签: .net clr heap