CHAPTER 18 UNDERSTANDING CIL AND THE ROLE OF DYNAMIC ASSEMBLIES
RunAndSave
Represents that a dynamic assembly can be executed in memory and saved
to disk
Save
Represents that a dynamic assembly can be saved to disk but not executed in
memory
The next task is to define the module set for your new assembly. Given that the assembly is a singlefile unit, you need to define only a single module. If you were to build a multifile assembly using the
DefineDynamicModule() method, you would specify an optional second parameter that represents the name
of a given module (e.g., myMod.dotnetmodule). However, when creating a single-file assembly, the name of
the module will be identical to the name of the assembly itself. In any case, once the DefineDynamicModule()
method has returned, you are provided with a reference to a valid ModuleBuilder type.
// The single-file assembly.
ModuleBuilder module =
assembly.DefineDynamicModule("MyAssembly", "MyAssembly.dll");
The Role of the ModuleBuilder Type
ModuleBuilder is the key type used during the development of dynamic assemblies. As you would expect,
ModuleBuilder supports a number of members that allow you to define the set of types contained within
a given module (classes, interfaces, structures, etc.) as well as the set of embedded resources (string
tables, images, etc.) contained within. Table 18-11 describes a few of the creation-centric methods. (Do
note that each method will return to you a related type that represents the type you want to construct.)
Table 18-11. Select Members of the ModuleBuilder Type
Method
Meaning in Life
DefineEnum()
Used to emit a .NET enum definition
DefineResource()
Defines a managed embedded resource to be stored in this module
DefineType()
Constructs a TypeBuilder, which allows you to define value types,
interfaces, and class types (including delegates)
The key member of the ModuleBuilder class to be aware of is DefineType(). In addition to specifying
the name of the type (via a simple string), you will also make use of the
System.Reflection.TypeAttributes enum to describe the format of the type itself. Table 18-12 lists some
(but not all) of the key members of the TypeAttributes enumeration.
Table 18-12. Select Members of the TypeAttributes Enumeration
Member
Meaning in Life
Abstract
Specifies that the type is abstract
Class
Specifies that the type is a class
689