Chapter 5. Generating code with Reflection.Emit

 

This chapter covers

  • Scenarios for generating code at runtime
  • A quick overview of opcodes
  • Building code with Reflection.Emit and DynamicMethod

In chapter 4, you saw how you can generate code via the CodeDOM. Another option in .NET lets you do the same thing, except it uses IL directly to create the code at runtime. This provides a substantial performance boost and access to any feature supported by the CLR. All the supporting classes exist in the System.Reflection.Emit namespace, and that’s where you’ll spend your time in this chapter. We cover how the common opcodes work, and then you’ll see examples that generate dynamic assemblies and methods.

The first thing you need to understand is why one would ever bother diving into the Emitter classes to solve particular problems. That’s what the next section discusses.

5.1. Why Emitter classes?

It’s probably a safe bet to assume that most of the code you’ve written in .NET has followed the same general workflow:

  • Write code in your favorite language
  • Compile it
  • Run the results

But what if you were able to write and compile code while your code was executing? Let’s cover some scenarios where the Emitter classes may come in handy in solving particular programming problems at runtime.

5.1.1. Support for DSLs

5.2. An overview of assembly internals

5.3. A lightning tour of opcodes

5.4. Creating dynamic assemblies

5.5. Lightweight code generation with dynamic methods

5.6. Summary

sitemap