Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Reflection, Attributes and Metadata

Reflection.Emit

Reference for System.Reflection.Emit in C#: DynamicMethod, AssemblyBuilder, TypeBuilder and ILGenerator to generate types and methods at run time.

System.Reflection.Emit lets a program write new code while it runs. You describe IL (intermediate language) instructions with an ILGenerator, and the runtime JIT-compiles them like any other method. There are two levels: DynamicMethod creates a single standalone method, while AssemblyBuilder, ModuleBuilder and TypeBuilder create whole types with fields, properties and methods in a dynamic assembly.

Most application code never needs it. Mocking libraries, ORMs, serializers and dependency-injection containers use it to generate proxies and fast accessors. For simple cases, expression trees are easier and safer, because they generate IL for you and check types.

C#
var method = new DynamicMethod("Add", typeof(int), [typeof(int), typeof(int)]);
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Ret);

Try it

C# DynamicMethod: add two numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# TypeBuilder: generate a class with a property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
new DynamicMethod(string name, Type returnType, Type[] parameterTypes)
AssemblyBuilder.DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)
assembly.DefineDynamicModule(string name)
module.DefineType(string name, TypeAttributes attributes)
Member Description
ILGenerator.Emit(OpCode, ...) Appends one instruction. Overloads take no operand, a field, method, type, label, string or number.
DefineLabel, MarkLabel, DeclareLocal Branch targets and local variables.
TypeBuilder.DefineField, DefineMethod, DefineProperty, DefineConstructor Add members.
TypeBuilder.CreateType() Bakes the type and returns the real Type.
AssemblyBuilderAccess Run (execute only) or RunAndCollect (can be unloaded).

Errors: wrong IL does not fail when you emit it but when the method is first jitted: InvalidProgramException: Common Language Runtime detected an invalid program. A stack that is not balanced at Ret is the classic cause.

Usage notes

  • IL is stack-based. Push operands, execute the operation, and make sure exactly one value (or none for void) remains before Ret.
  • Debugging is hard. Emit small pieces, test each, and compare against what csc emits for the same C# (use a decompiler or ildasm).
  • .NET 9 added PersistedAssemblyBuilder, which can save an assembly to disk; AssemblyBuilder.DefineDynamicAssembly stays in memory only.
  • Prefer DynamicMethod or expression trees for a single function; reach for TypeBuilder only when you need a new type, such as a proxy that implements an interface.
  • Visibility: pass skipVisibility: true (via the DynamicMethod owner constructor) to touch private members; use sparingly.
  • Native AOT and trimming: run-time code generation is unavailable in Native AOT. See Native AOT and trimming.
  • Alternatives: source generators generate code at build time and are safe for AOT.