Emitting MSIL Instructions with Reflection Emit

The ILGenerator class provides methods that can be used to emit Microsoft intermediate language (MSIL). The ConstructorBuilder.GetILGenerator method returns an ILGenerator for a constructor. The MethodBuilder.GetILGenerator method returns an ILGenerator for a method.

Note

When dynamic methods are executed, the just-in-time (JIT) compiler is called to convert the MSIL to native code. Exceptions can be thrown at this point. For example, InvalidProgramException can be thrown if the method body exceeds an internal limitation, such as the maximum allowed size. TargetInvocationException can be thrown, with an inner VerificationException exception, if SkipVerification is refused in order to force verification of the emitted MSIL. Refusing SkipVerification during development is recommended, because verifying code improves program stability and quality.

The following services are provided by the ILGenerator class:

  • Emit various kinds of instructions using different forms of ILGenerator.Emit methods. These instructions take different kinds of operands depending on the type of instruction.

  • Declare a label. The position of the label in the instruction stream is specified using a different method.

  • Mark a position in the MSIL stream with a label.

  • Throw an exception.

  • Write a line to the console.

  • Define an exception block.

    • ILGenerator.BeginExceptionBlock begins an exception block.

    • ILGenerator.BeginExceptFilterBlock begins a filtered exception handler.

    • ILGenerator.BeginCatchBlock begins a typed exception handler.

    • ILGenerator.BeginFinallyBlock begins a finally handler.

    • ILGenerator.BeginFaultBlock begins a fault handler.

    • ILGenerator.EndExceptionBlock ends an exception block.

For catch handlers, the sequence of calls should resemble the following template:

Emit some MSIL.
BeginExceptionBlock
Emit the MSIL for the try block.
BeginCatchBlock
Emit the MSIL for the handler.
BeginCatchBlock
Emit the MSIL for the handler.
BeginFaultBlock
Emit the MSIL for the fault block.
BeginFinallyBlock
Emit the MSIL for the finally block.
EndExceptionBlock

For filtered handlers, the sequence of calls should resemble the following template:

Emit some MSIL.
BeginExceptionBlock
Emit the MSIL for the try block.
BeginExceptFilterBlock
Emit the MSIL for the filtered exception handler.
BeginCatchBlock
Emit the MSIL for the catch block. The catch handler should be supplied with a null type.
BeginFaultBlock
Emit the MSIL for the fault block.
BeginFinallyBlock
Emit the MSIL for the finally block.
EndExceptionBlock

See Also

Other Resources

Using Reflection Emit