Listing 1: The HelloReflectionEmit class
using System; using System.Reflection; using System.Reflection.Emit; class HelloReflectionEmit { static void Main() { // Create a (weak) assembly name AssemblyName an = new AssemblyName(); an.Name = "HelloReflectionEmit"; // Define a new dynamic assembly (to be written to disk) AppDomain ad = AppDomain.CurrentDomain; AssemblyBuilder ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Save); // Define a module for this assembly ModuleBuilder mb = ab.DefineDynamicModule(an.Name, "Hello.exe"); // namespace Foo { public class Bar { ... } } TypeBuilder tb = mb.DefineType("Foo.Bar", TypeAttributes.Public| TypeAttributes.Class); // The leg bone's connected to the knee bone... MethodBuilder fb = tb.DefineMethod("Main", MethodAttributes.Public| MethodAttributes.Static, typeof(int), new Type[] {typeof(string[])}); // Write the ubiquitous "Hello, World!" method, in IL ILGenerator ilg = fb.GetILGenerator(); ilg.Emit(OpCodes.Ldstr, "Hello, World!"); ilg.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] {typeof(string)} )); ilg.Emit(OpCodes.Ldc_I4_0); ilg.Emit(OpCodes.Ret); // Seal the lid on this type Type t = tb.CreateType(); // Set the entrypoint (thereby declaring it an EXE) ab.SetEntryPoint(fb,PEFileKinds.ConsoleApplication); // Save it ab.Save("Hello.exe"); // Done! Console.WriteLine("File saved: {0}", "Hello.exe"); } }