irst, a quick review of exactly what reflection is and what it is used for. From Part 1, you know that "Reflection is a means of discovering information about objects at runtime and executing against those objects." This functionality is provided in .NET by the System.Reflection namespace. Classes in this namespace, including Assembly, Module, ConstructorInfo, MethodInfo, and others, are used for type discovery and dynamic invocation. Put simply, they allow you to both explore the classes, methods, properties, and fields (types) exposed by an assembly as well as create an instance of a type and execute one of its methods (invoke members). While these features are great for run-time object discovery, reflection in .NET does not stop there. Reflection also allows you to build assemblies and create entirely new types at run-time. This is known as reflection emit
What Is Reflection Emit?
Nested under System.Reflection is the System.Reflection.Emit namespace, which is home for all of the Framework classes that allow you to dynamically build assemblies and types from scratch. Although the very act of generating code on demand is likely a feature that few developers will ever need, it is a credit to the .NET Framework that the tools are there, waiting for the right business problem to solve.
As an example, using reflection emit it would be possible to:
- Create a new assembly. (Assemblies can be "dynamic" in that they exist only in memory, or can be persisted to disk.)
- Within the assembly, create a module.
- Within the module, create a type.
- Add properties and methods to that type.
- Generate the code inside of the method or property.
As it turns out this is actually the exact process you will follow when you use the Reflection.Emit classes to generate code.
(See Sidebar: Constructors)
(See Sidebar: ILDASM)
(See Sidebar: Generating Executables)