Book Image

Metaprogramming in C#

By : Einar Ingebrigtsen
Book Image

Metaprogramming in C#

By: Einar Ingebrigtsen

Overview of this book

Metaprogramming is an advanced technique that helps developers to automate repetitive tasks, generate scalable code, and enhance productivity in software development. Metaprogramming in C# is a comprehensive guide that will help you reap the full potential of metaprogramming in .NET runtime. You’ll start by learning about the .NET runtime environment and how you can use it to become a more productive developer. You'll learn how to infer types using reflection, use attributes, and create dynamic proxies. You’ll also explore the use of expressions to create and execute code and how to take advantage of Dynamic Language Runtime. But that's not all! You’ll also learn to go beyond inheritance and use method signature conventions to create easily maintainable code. Finally, you’ll dive into the world of compiler magic with Roslyn, where you'll discover how to use Roslyn to generate code, perform static code analysis, and write your own compiler extensions. By the end of this book, you’ll have a deep understanding of metaprogramming concepts and how to apply them to your C# code. You’ll be able to think about types, use attributes and expressions to generate code, and apply crosscutting concerns to improve code quality.
Table of Contents (25 chapters)
1
Part 1:Why Metaprogramming?
5
Part 2:Leveraging the Runtime
12
Part 3:Increasing Productivity, Consistency, and Quality
18
Part 4:Compiler Magic Using Roslyn

What are cross-cutting concerns?

As the lead-in to the chapter suggests, you might find yourself in your project with guidelines, formalized or not, that give you recipes for how to do things. For instance, to write a representational state transfer (REST) API that performs actions in your application, you might have a list of things defined that is there to help you remember what to do:

  • Check authorization
  • Check whether the input is valid
  • Check whether the action is allowed as per business rules
  • Add logging for the action
  • Perform the action by calling the domain logic
  • Translate the result from the domain to something digestible for REST consumption
  • Remember to wrap the call to the domain in try {} catch {} and return the correct error

For each of these steps, there is always the risk that the developer will forget. This can pose a risk, cause security issues, data consistency, or other problems.

Personally, I’m a huge fan of automating...