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) }));



            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.


Comments (22)
  1. There seems to be a fair amount of recent press and blog action surrounding the dynamic or “scripting”…

  2. There seems to be a fair amount of recent press and blog action surrounding the dynamic or “scripting”…

  3. BM Bloggers says:

    With my current implementation of the GUITesting framework integrated with Test Projects within VS.Net,…

  4. Have you ever tried DynamicMethod, one of the coolest features in the .NET 2.0? Hope you have; otherwise,

  5. I mentioned earlier that you can debug Reflection.Emit code . Unfortunately, Ref.Emit code can’t be unloaded

Comments are closed.

Skip to main content