namespace ReflectionEmitHelloWorld { using System; using System.Reflection; using System.Reflection.Emit; class Program { static void Main(string[] args) { // Define the assembly and module const string AssemblyName = "Badflyer.HelloWorld.dll"; var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(AssemblyName), AssemblyBuilderAccess.RunAndCollect); var module = assembly.DefineDynamicModule(AssemblyName); // Define the method and get the Intermediate Language generator. var methodBuilder = module.DefineGlobalMethod("HelloWorld", MethodAttributes.Final | MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[0]); var ilGenerator = methodBuilder.GetILGenerator(); //// Too easy - but this works too // ilGenerator.EmitWriteLine("Hello World"); // Get the method info for writeline var writeline = typeof(Console).GetMethod("WriteLine", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder, new[] { typeof(string) }, null); // Load the string onto the evaluation stack ilGenerator.Emit(OpCodes.Ldstr, "Hello World"); // Call writeline ilGenerator.EmitCall(OpCodes.Call, writeline, new[] { typeof(string) }); // Return ilGenerator.Emit(OpCodes.Ret); // Create the global functions (since that is what we defined) module.CreateGlobalFunctions(); // Get our new method info var helloWorld = module.GetMethod("HelloWorld"); // Invoke our new method. helloWorld.Invoke(null, null); // Wait for input Console.ReadLine(); } } }