Understanding the CLR via its assembly code

Expert .NET 2.0 IL Assembler by Serge Lidin

I have read large parts of this book multiple times, but have never sat down and read it cover to cover before. It’s a great book for understanding the CLR. The book isn’t just about IL assembly language as a programming language. The book covers this but also covers the translated form of the IL, discussing the format and sections of a PE file including the various metadata tables of the various types (think assembly or module or class) and heaps. It also gives a great explanation of the various IL instructions and discusses the semantics of generics and exceptions. All in all, I think it is a great book for understanding the CLR and I always (re)learn something every time I reread it.

For example, when you want to call the methods on a valuetype via an interface, you typically need to box it. If the struct is not mutable this is usually not the semantics you want. When you instantiate a generic class using a structure type, the user would like the interface method to be invoked without any boxing, and the CLR version 2 got a new IL instruction, constrained to deal with this.

class Holder<T> where T : IFoo
T field;
public Holder(T x)
field = x;
public void DoInc()

leads to the following code for the DoInc method

IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldflda !0 class ConsoleApplication10.Holder`1<!T>::’field’
IL_0007: constrained. !T
IL_000d: callvirt instance void ConsoleApplication10.IFoo::Increment()
IL_0012: nop
IL_0013: ret

The book also warns you of some of the times when C# isn’t the assembly language of .NET… if you satisfy an interface using a non-virtual method, the C# compiler silently makes it sealed virtual, or if you nest a non-generic class inside a generic class the compiler silently makes the nested class generic so that you have access to the type parameter.

The book teaches you loads of miscellaneous facts about the CLR – debug information and various security attributes for example, and how unmanaged mixed-mode assemblies work. The emphasis on using ILDASM/ILASM to round trip code with modification is also very informative.

A thoroughly great book!

This entry was posted in Books. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s