hello, world... LCG (Lightweight Code Gen) style!

I've finally gotten around to cooking up a post about the the spectrum of late-bound invocations one may make over methods, and it includes a look at a new Whidbey feature called LCG (Lightweight Code Gen). I'll be posting the invocation story very soon, but I figured I'd give a very brief overview of LCG first: LCG provides runtime code generation facilities for emitting global static methods. It looks and feels much like Reflection.Emit but sharpens its focus to just the generation of methods and their IL. It's lighter than RE, and targets scenarios like late-bound invocation, serialization, partial evaluation and runtime code generation. It's contrast to RE looks something like the following:

  • Static methods only.
  • Doesn't incur the overhead of generating new assemblies, modules and types.
  • Generated methods are able to be reclaimed.
  • Has the ability to skip JIT-time visibility checks, given appropriate permissions.

Enough of the overview, on to the traditional hello, world app:

using System;

using System.Reflection;

using System.Reflection.Emit;

public class LCGHelloWorld

{

      public static void Main(string[] args)

      {

            DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(void), new Type[] {}, typeof(LCGHelloWorld), false);

            ILGenerator il = dm.GetILGenerator();

            il.Emit(OpCodes.Ldstr, "hello, world");

            il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));

            il.Emit(OpCodes.Ret);

            dm.Invoke(null, null);

      }

}

Notice the lack of Assembly, Module and Type builders. It's as simple as that - cook up a DynamicMethod and fire. You can find the very preliminary msdn style docs here - expect the documentation to solidify closer to the Beta 1 drop. In the meantime, have a play on the Whidbey PDC bits.

Enjoy.