Chapter 6. Generating code with expressions

 

This chapter covers

  • Using code as data
  • Using the power of expression trees
  • Improving code with expressions

As you saw in chapter 5, you can use the Reflection.Emit APIs to create dynamic code that you can execute at runtime. This requires intimate knowledge of IL. Let’s be honest: learning IL isn’t a skill set that most .NET developers have, nor is it one they necessarily want to acquire, even if they’re interested in metaprogramming techniques. The reason is simple: writing code in IL can easily lead to incorrect implementations and requires a mental model of code execution in .NET that’s not as intuitive as the one a high-level language provides.

Fortunately, there’s another API in .NET that lets you create code without having to know anything about IL. This is the Expression API that exists within the LINQ world. In this chapter, you’ll see how you can view your code as data in a way that will make metaprogramming much easier to do in .NET. When something is easier to accomplish, you end up using it more, which is why learning about expressions to generate dynamic code is advantageous. You’ll end up seeing scenarios in your code where you can use expressions to handle certain problems elegantly. Let’s start by looking at how expressions work at a higher level.

6.1. Expression-oriented programming

6.2. Making dynamic methods with LINQ Expressions

6.3. Using expressions effectively

6.4. Evolving expression trees

6.5. Summary

sitemap