Friday, 28 September 2007

System.Reflection.Emit wonders!

As I've said in one of first posts, one of the more exciting feature of CLR platform is the ability to create executable .NET code from another .NET program.
When you compile a source for .NET/CLR platform, the compiler translate the specific language syntax (C#, VB.NET, Managed C++, etc) in bytecode compatible with the CLR Virtual Machine.
The amazing thing is that you can create this bytecode using standard .NET API: System.Reflection and System.Reflection.Emit. For a simple but very useful demonstration follow this link to Joel Pobar's CLR weblog: the post explain how to create a classic "HelloWorld Program" using these APIs.

I hope that this example shows you how much this programmer tool can be powerful. The other important thing that I must to point out, is that dynamic code can be executed without being written to disk (therefore in memory).

This argument is too big for a single post; so I will back on Reflection.Emit, digging more deeper in these bits!
For the ones that can't wait, some useful links...

[1] CIL: the CLR assembler, formerly known as MSIL.
[2] Cecil: a powerful API (for inspect and generate CLR bytecode).
[3] PostSharp: a tool able to modify assembly injecting bytecode instructions (CIL)