Playing with IL generation

This week I started learning how to generate CIL (Common Intermediate Language, the .NET runtime’s equivalent of assembly). The .NET classes for doing this looked a bit intimidating so I chose to try out FluentIL first. FluentIL is a helper library to simplify generating IL. I’m not sure if it helped or hurt–I had to mentally translate all the online samples I looked at into FluentIL and I also found an opcode (castclass) which wasn’t implemented in the fluent helpers.

I used the cheater method to write the example below. First I wrote a strongly typed C# method which did exactly what I wanted the IL to do and built it in release mode. Then I used dotPeek to view the generated IL and wrote an equivalent generic version.

One of the difficulties of writing IL is debugging it. If the program isn’t perfectly valid, the runtime gives you a very generic invalid program error. Also, if you have a runtime type violation in the IL you get an exception saying the operation could make the runtime unstable. There is no stack trace to help you find the error.

This code provides a way to directly set properties on an object without using reflection. It would be useful if you have an object but only know the type at runtime. This isn’t production ready code.