Chapter 8: Dynamic Code Generation

Overview

In this chapter we are going to investigate a significant, though often under used, feature that is offered by the .NET Framework classes - the ability to generate either source code or IL code dynamically. In other words, having your code actually write or manipulate code instead of data. Normally, you would conceptually imagine that the process of producing a software application involves you writing the source code, compiling it, and shipping it - and that's it. The code and resources your organization wrote constitutes the totality of the shipped product. With dynamic code generation, however, your shipped code can itself actually generate new code to perform additional tasks - this can be useful for performance reasons, among other factors. Alternatively, your code might modify the code in other assemblies (which might be done, for example, to insert calls to create debugging or profiling information). And obviously, if your product is a developer tool that is intended to assist developers in writing code, then it may be called on to generate some source code itself.

This chapter will cover:

  • Applications of Dynamic Code Generation - I'll review the main reasons why you might find it useful to use dynamic code generation.

  • Architecture - the design of the code generation classes, and in particular the different philosophies behind the System.Reflection.Emit classes (which generate straight assemblies containing IL code) and the System.CodeDom classes (which generate source code or assemblies).

  • Examples - the bulk of the chapter is devoted to a couple of examples that illustrate how to use the dynamic code generation classes. For this part of the chapter, we treat the Reflection.Emit and the CodeDom classes separately.

Dynamic code generation is not something that has any substantial intrinsic support in the CLR - it is a feature that is supported almost entirely by the associated .NET class libraries supplied by Microsoft. Hence this chapter focuses almost exclusively on the use of the relevant classes. Note, however, that I'm not going to make any attempt to be comprehensive, for example to give lists of all the methods implemented by particular classes. You can find out that stuff easily enough in the MSDN documentation. Rather, my aim here is to give you a feel for how the classes are used, and how they have been designed.



Advanced  .NET Programming
Advanced .NET Programming
ISBN: 1861006292
EAN: 2147483647
Year: 2002
Pages: 124

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net