Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where the 'Type' of a reference value is stored in memory?

As the reference values are stored in the heap as a data; where do the type information of any reference value is stored?

If there are a couple of instances of class Artist; when they are stored in the heap how the .Net tags those memory blocks as type of Artist?

thanks!

like image 893
pencilCake Avatar asked Dec 28 '22 20:12

pencilCake


1 Answers

void M()
{
   Artist a = new Artist();
}

When the method is called, a new stack frame is expanded, CLR has some preparation code before the first statement of the method is executed, like a prolegomenon. During this period, CLR loads all types used in the method. In this example, type of Artist will be loaded to heap. But it is also possible that the type is already there, because the type is used before M() is invoked. Then we come to the first expression, a new statement, which invokes the constructor of the class. If you take a look at the CIL it generated, you will see something like newobj blabla. Here a block of memory on the heap are allocated for the storage of the instance. The size of the block depends on the details of the class, because the block needs to hold all the data of the instance. Usually the block is made up by:

Type pointer + Sync root + Instance data

The type pointer points to its type on the heap(loaded in the prolegomenon). The sync root is a record for lock and synchronization. The instance data stores the members' data of the instance.

like image 153
Cheng Chen Avatar answered Jan 10 '23 16:01

Cheng Chen