Phase 10 of 30 · Topic 10.4

Dynamic Method Compilation via `System.Reflection.Emit.DynamicMethod`

1Concept

`DynamicMethod` generates high-speed IL bytecode on the fly at runtime, generating custom serializers and property accessors that run at compiled native speed without reflection overhead.

2Architecture Diagram

Property Access via Reflection: 15-25ns (Slow)
Property Access via DynamicMethod IL: 0.5ns (Identical to compiled C# code!)

3Code Example

C# 13 & .NET 9
using System;
using System.Reflection.Emit;

public class DynamicMethodDemo
{
    public static void Main()
    {
        // Create dynamic method: int Square(int x)
        var dynMethod = new DynamicMethod(
            name: "FastSquare",
            returnType: typeof(int),
            parameterTypes: new[] { typeof(int) }
        );

        var il = dynMethod.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0); // Load argument 0
        il.Emit(OpCodes.Dup);     // Duplicate value on evaluation stack
        il.Emit(OpCodes.Mul);     // Multiply: x * x
        il.Emit(OpCodes.Ret);     // Return result

        var squareFunc = (Func<int, int>)dynMethod.CreateDelegate(typeof(Func<int, int>));
        Console.WriteLine($"Dynamic IL FastSquare(8): {squareFunc(8)}");
    }
}

4Expected Output

Dynamic IL FastSquare(8): 64

5Key Takeaways

  • `DynamicMethod` powers high-speed libraries like Dapper and AutoMapper.
  • Bypasses standard reflection lookup overhead.
  • Note: Dynamic IL emission is restricted in Native AOT environments.