Monday 22 June 2009

Using Expression when creating runtime types

In .NET 3.5, the framework provides the (greatly appreciated) mechanism to compile an expression tree to a delegate - providing a convenient way to write dynamic methods without having to dabble in IL (never pretty).

Over the weekend, I've been looking in more depth at the DLR trees in 4.0 (beta) - and an interesting little nugget leapt out at me... you can now compile an expression tree into the body of a MethodBuilder! This means that even when writing a full type at runtime you can write the methods using an object model rather than Reflection.Emit.

My current example of this doesn't really illuminate much, so I won't post it "as is" - probably to follow. But does this sound "time" for people having to learn how to use ILGenerator?

Don't get me wrong - expression trees aren't trivial, and you need to think carefully when writing them - but they are a lot simpler than writing IL directly.