Wednesday 29 December 2010

ValueTypes GetType

Yesterday, thinking a bit again about how .Net types get described through the MethodTable and EEClass combination (check previous entries), I came up with a question, how does this work for structs (well, value types in general)?

.Net Reference types have a 8 bytes overhead, due to the SyncBlock index and the Type Information pointer (a pointer to the Method Table, which in turn points to the EEClass). You can read more here. It's important to indicate that an Object reference points to the 4 bytes where the pointer to the Method Table lies, after that come the DataFields, and before that is the SyncBlock.

[SyncBlock(4 bytes) | pointer to the Method Table(4 bytes) | Data Fields]

So it's easy to assume that Object.GetType() makes use of the info in the Method Table to return the Type object. I've said assume cause it can't be confirmed by Reflector. If we disassemble the code we end up with this:
[MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical]
which means that it's implemented internally within the system itself...


However, structs do not have any extra information, they exist just for performance reasons, not for any semantic reason, and were designed as lightweight as possible (read more here)

and there are structs, which are lightweight data types for storage but allow object-like method calls for familiarity and convenience.

So, if we don't have a pointer to the Type information, how does the Runtime determine the type of a value type? As usual, StackOverflow to the rescue (the question is not mine, somebody else had already been tormeted by this doubt).
As someone perfectly explains, it's the compiler who really takes care of it, not the runtime. When calling myValueType.GetType(), myValueType gets boxed, and that boxing operation involves storing onto the stack the Type for myValueType.

Memory layout of .Net objects (from this excellent article)

Value Types:


Reference Types:

No comments:

Post a Comment