Namespace System.Reflection.Emit
Provides classes that allow a compiler or code generator to create an intermediate language (IL) stream that can be saved to a portable executable (PE) file. You can use these classes to emit dynamically generated code.
Summary
Classes
- AssemblyBuilder Class
- ConstructorBuilder Class
- CustomAttributeBuilder Class
- DynamicMethod Class
- EnumBuilder Class
- EventBuilder Class
- FieldBuilder Class
- GenericTypeParameterBuilder Class
- ILGenerator Class
- Label Struct
- LocalBuilder Class
- MethodBuilder Class
- ModuleBuilder Class
- ParameterBuilder Class
- PropertySet Class
- TypeBuilder Class
Details
The classes in this namespace are primarily used for late-bound access to code that is generated at run time. This is often referred to as dynamic code generation.
Key Concepts
- ILGenerator: This class provides methods for emitting Microsoft intermediate language (MSIL) instructions.
- TypeBuilder: Use this class to define new types dynamically.
- MethodBuilder: Use this class to define new methods dynamically.
- AssemblyBuilder: Represents a dynamic assembly that is being generated.
Example Usage
The following example demonstrates how to create a simple dynamic assembly and a type with a method using AssemblyBuilder
and TypeBuilder
.
using System;
using System.Reflection.Emit;
using System.Reflection;
public class DynamicCodeGenerator
{
public static void CreateDynamicAssembly()
{
// Define the assembly name
var assemblyName = new AssemblyName("MyDynamicAssembly");
// Create the assembly builder
var assemblyBuilder = System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
// Get the module builder
var moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
// Define a new type
var typeBuilder = moduleBuilder.DefineType("MyDynamicClass", TypeAttributes.Public);
// Define a method
var methodBuilder = typeBuilder.DefineMethod(
"SayHello",
MethodAttributes.Public,
typeof(void),
null // No parameters
);
// Get the IL generator for the method
var ilGenerator = methodBuilder.GetILGenerator();
// Emit instructions to print "Hello, World!"
ilGenerator.EmitWriteLine("Hello, World!");
ilGenerator.Emit(OpCodes.Ret); // Return from the method
// Create the type
var dynamicType = typeBuilder.CreateType();
// Create an instance of the dynamic type
var instance = Activator.CreateInstance(dynamicType);
// Get the method info
var methodInfo = dynamicType.GetMethod("SayHello");
// Invoke the method
methodInfo?.Invoke(instance, null);
}
}
When this code is executed, it will dynamically create an assembly, define a type within it, define a method that prints "Hello, World!" to the console, and then invoke that method.