/* This Example is a part of different * examples shown in Book: * C#2005 Beginners: A Step Ahead* Written by: Gaurav Arora * Reach at : msdotnetheaven*/// File name : dynamicAssembly.cs//This demostrates how to build a dynamic assemblyusing System;using System.Reflection;using System.Reflection.Emit;namespace CSharp.AStepAhead.dynamicAssembly{ class CodeGenerator { Type t; AppDomain currentDomain; AssemblyName assemName; AssemblyBuilder assemBuilder; ModuleBuilder moduleBuilder; TypeBuilder typeBuilder; MethodBuilder methodBuilder; ILGenerator msilG; public static void Main() { CodeGenerator codeGen = new CodeGenerator(); Type myType = codeGen.T; if (myType != null) { object o = Activator.CreateInstance(myType); MethodInfo helloWorld = myType.GetMethod("HelloWorld"); if (helloWorld != null) { // Run the HelloWorld Method helloWorld.Invoke(o, null); } else //if method info null { Console.WriteLine("Could not retrieve MethodInfo"); } } else //if type null { Console.WriteLine("Could not access the Type"); } } public CodeGenerator() { // Get the current Application Domain. // This is needed when building code. currentDomain = AppDomain.CurrentDomain; // Create a new Assembly for Methods assemName = new AssemblyName(); assemName.Name = "dynamicAssembly"; assemBuilder = currentDomain.DefineDynamicAssembly(assemName, AssemblyBuilderAccess.Run); // Create a new module within this assembly moduleBuilder = assemBuilder.DefineDynamicModule("dynamicAssemblyModule"); // Create a new type within the module typeBuilder = moduleBuilder.DefineType("dynamicAssemblyClass", TypeAttributes.Public); // Now add the HelloWorld method to the class that was just created. methodBuilder = typeBuilder.DefineMethod("HelloWorld", MethodAttributes.Public, null, null); // Now generate some Microsoft Intermediate Language Code that simply // writes a line of text out to the console. msilG = methodBuilder.GetILGenerator(); msilG.EmitWriteLine("Hello! This is a dynamic assembly."); msilG.Emit(OpCodes.Ret); // Create a type. t = typeBuilder.CreateType(); } public Type T { get { return this.t; } } }}