OpCodes.Ldtoken

Posted on March 31, 2016 · 1 min read · tagged with: #MSIL #RampUpNet

You probably used typeof operator a few times. It’s quite funny, that an operator like this actually has no MSIL counterpart. Using it emits TWO OpCodes.

The first emitted opcode is OpCodes.Ldtoken with the type. It consumes the token of the type, pushing the RuntimeTypeHandle structure onto the stack as the result of its operation. The second emitted code is a call to the Type.GetTypeFromHandle(RuntimeTypeHandle) which consumes the structure pushed by the previous code, returning the runtime type. The interesting thing is that you can’t use just OpCodes.Ldtoken from C#. You need to load the runtime type first and then you can access the handle by a property. You can emit IL with just OpCodes.Ldtoken though to remove overhead of calling a method and use the structure as a key for a lookup. It will be a bit faster for sure.

You can see the example of emitting this in RampUp code of the message writer.