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

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

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.