Browse DevX
Sign up for e-mail newsletters from DevX


Reflection Part II: Emit

In our previous article, Reflection Part 1: Discovery and Execution , we introduced the System.Reflection namespace and its classes which allow developers to view assembly metadata, query for and discover types, and invoke code—all at run-time. In this article we will examine reflection emit—the ability to dynamically generate code at runtime.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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:

  1. Create a new assembly. (Assemblies can be "dynamic" in that they exist only in memory, or can be persisted to disk.)
  2. Within the assembly, create a module.
  3. Within the module, create a type.
  4. Add properties and methods to that type.
  5. 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)

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date