Tuesday, September 27, 2011

Internals of .NET Objects and Use of SOS

Well, now getting deeper into the facts, lets talk about how objects are created in .NET and how type system is laid out in memory for this post in my Internals Series.  As this is going to be very deep dive post, I would recommend to read this only if you want to kill your time to know the internal details of .NET runtime and also you have considerable working experience with the CLR types and type system.


Recently I have been talking with somebody regarding the actual difference between the C++ type system and managed C# type system. I fact the CLR Type system is different from the former as any object (not a value type) is in memory contains a baggage of information when laid out in memory. This makes CLR objects considerable different from traditional C++ programs.

Classification of Types

In .NET there are mainly two kind of Types.

    Value Types (derived from System.ValueType)
    Reference  Type (derived directly from System.Object)

Even though ValueTypes are internally inherited from System.Object in its core, but CLR treats them very differently.  Indeed from your own perception the Value Types are actually allocated in stacks (occationally) while reference types are allocated in Heaps. This is to reduce the additional contension of GC heaps for Heap allocation, GC cycles, occasional call to OS for additional memory needs etc. The object that is allocated in managed Heap is called Managed Object and the pointer that is allocated in stack to refer to the actual object in heap is called Object Reference (which is sometimes called as Managed Pointer).


Additional to this basic difference a Value Type is treated completely different from CLR point of view. CLR treats any object that is derived from System.ValueType differently in respect of any other object derived from System.Object directly. The memory of a ValueType contains just the value of its fields and the size of the Value Type is just the addition to its content, while for reference types the size is completely different. Let us consider looking at the memory layout of both the types.

stack.PNG
In case of Value Types, the Managed Pointer holds reference to the initial location of the actual Memory.Thus in this case, the Managed pointer holds reference to 0x0000 which is the address location of Field 1. Hence CLR needs to do pointer arithmetic to find Fields ... N.  Thus we can easily use Sizeof operator on ValueTypes to get the actual size of the object.

Read more: DOT NET TRICKS
QR: internals-of-net-objects-and-use-of-sos.html

Posted via email from Jasper-Net