Free mag vol1 | Page 741

CHAPTER 18  UNDERSTANDING CIL AND THE ROLE OF DYNAMIC ASSEMBLIES • You want to load a static assembly and dynamically insert new types into the binary image. Several aspects of the .NET runtime engine involve generating dynamic assemblies quietly in the background. For example, ASP.NET makes use of this technique to map markup and server-side script code into a runtime object model. LINQ also can generate code on the fly, based on various query expressions. This being said, let’s check out the types within System.Reflection.Emit. Exploring the System.Reflection.Emit Namespace Creating a dynamic assembly requires you to have some familiarity with CIL opcodes, but the types of the System.Reflection.Emit namespace hide the complexity of CIL as much as possible. For example, rather than directly specifying the necessary CIL directives and attributes to define a class type, you can simply make use of the TypeBuilder class. Likewise, if you want to define a new instance-level constructor, you have no need to emit the specialname, rtspecialname, or .ctor tokens; rather, you can make use of the ConstructorBuilder. Table 18-8 documents the key members of the System.Reflection.Emit namespace. Table 18-8. Select Members of the System.Reflection.Emit Namespace 684 Members Meaning in Life AssemblyBuilder Used to create an assembly (*.dll or *.exe) at runtime. *.exes must call the ModuleBuilder.SetEntryPoint() method to set the method that is the entry point to the module. If no entry point is specified, a *.dll will be generated. ModuleBuilder Used to define the set of modules within the current assembly. EnumBuilder Used to create a .NET enumeration type. TypeBuilder May be used to create classes, interfaces, structures, and delegates within a module at runtime. MethodBuilder LocalBuilder PropertyBuilder FieldBuilder ConstructorBuilder CustomAttributeBuilder ParameterBuilder EventBuilder Used to create type members (such as methods, local variables, properties, constructors, and attributes) at runtime. ILGenerator Emits CIL opcodes into a given type member. OpCodes Provides numerous fields that map to CIL opcodes. This type is used in conjunction with the various members of System.Reflection.Emit.ILGenerator.