DynamicMethod Class
The DynamicMethod class provides a way to create a method at runtime with a custom signature and implementation. It can be used for emitting IL directly, creating lightweight delegates, or defining methods that can be attached to a type.
Namespace
System.Reflection.Emit
Assembly
mscorlib.dll
Syntax
public sealed class DynamicMethod : MethodInfo
Constructors
| Signature | Description |
|---|---|
DynamicMethod(string name, Type returnType, Type[] parameterTypes) |
Creates a dynamic method with the specified name, return type, and parameter types. The method is private to the defining assembly. |
DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) |
Associates the dynamic method with a specific owner type, allowing access to its private members. |
DynamicMethod(string name, Type returnType, Type[] parameterTypes, Module m) |
Creates the method in the context of a particular module. |
DynamicMethod(string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) |
Specifies whether the dynamic method can bypass visibility checks. |
Key Members
| Member | Signature | Description |
|---|---|---|
| GetILGenerator | ILGenerator GetILGenerator() |
Returns an ILGenerator to emit the method's body. |
| CreateDelegate | Delegate CreateDelegate(Type delegateType) |
Creates a delegate of the specified type that represents the dynamic method. |
| Invoke | object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) |
Invokes the dynamic method directly. |
| InitLocals | bool InitLocals { get; set; } |
Gets or sets whether the local variables are automatically zero-initialized. |
Example
// Create a dynamic method that adds two integers
var dm = new DynamicMethod(
"Add",
typeof(int),
new[] { typeof(int), typeof(int) },
typeof(Program).Module);
ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Load first argument
il.Emit(OpCodes.Ldarg_1); // Load second argument
il.Emit(OpCodes.Add); // Add them
il.Emit(OpCodes.Ret); // Return result
var add = (Func<int, int, int>)dm.CreateDelegate(typeof(Func<int, int, int>));
Console.WriteLine(add(5, 7)); // Output: 12
Remarks
Dynamic methods are emitted in-memory and do not require a physical assembly on disk. They are ideal for scenarios where performance-critical code needs to be generated at runtime, such as serialization, LINQ providers, or dynamic proxies.
When using skipVisibility, be aware of security implications, as it can grant access to private members.