Free mag vol1 | Page 745

CHAPTER 18  UNDERSTANDING CIL AND THE ROLE OF DYNAMIC ASSEMBLIES // Create the SayHello method. MethodBuilder sayHiMethod = helloWorldClass.DefineMethod("SayHello", MethodAttributes.Public, null, null); methodIL = sayHiMethod.GetILGenerator(); methodIL.EmitWriteLine("Hello from the HelloWorld class!"); methodIL.Emit(OpCodes.Ret); // "Bake" the class HelloWorld. // (Baking is the formal term for emitting the type.) helloWorldClass.CreateType(); } // (Optionally) save the assembly to file. assembly.Save("MyAssembly.dll"); Emitting the Assembly and Module Set The method body begins by establishing the minimal set of characteristics about your assembly, using the AssemblyName and Version types (defined in the System.Reflection namespace). Next, you obtain an AssemblyBuilder type via the instance-level AppDomain.DefineDynamicAssembly() method (recall the caller will pass in an AppDomain reference into the CreateMyAsm() method), like so: // Establish general assembly characteristics // and gain access to the Assemb