CodeDom – An Advance Technique For Code Generation at Run Time
CodeDom, which stands for Code Document Object Model, is one advance technique provided by Microsoft.Net Framework to generate code at run-time. At application level, it gives programmers the capability to write a single language-independent code that can emit source code in a specific language for later requirements.
Code Document Object Model lies within the System.CodeDom namespaces of the.NET Framework. The CodeDom has the following advantages:
- From a single code that utilizes the CodeDom to represent the structure of source code that can generate source code of any language supports the CodeDom specification.
- The CodeDom allows source code and assemblies to be created, compiled, and executed dynamically at runtime.
- It provides a language independent object model for representing the structure of source code in memory.
- It acts as a source code translator among different languages.
Common usages of the CodeDOM include:
- Generating template code for emitting code wizards, coding examples, XML Web services client proxies, etc.
- Dynamically compiling code in languages supported.
T4 (Text Template Transformation Toolkit) is another powerful generation tool provided by Microsoft.net Framework. Unlike the CodeDom, T4 uses string concatenation to create textual template to generate code. A lot of the output code will be put into template blocks, in order to make the code generator easy to create and customize. However, T4 is a language dependent and will need a separate code generator for each output language. On the other hand, the CodeDom enables developers use a single source code to generate the same thing in different languages, which obviously give a huge advantage in developing.Net Framework tools.
Most programing constructs, including declarations, statements, arrays, casts, iterations, error handling and others, is supported by the CodeDom. For programing constructs that are not presently supported in CodeDom, “snippet” classes including the CodeSnippetCompileUnit, CodeSnippetExpression, CodeSnippetStatement, and CodeSnippetTypeMember can be used as generic representation. For generating code in a particular language, a corresponding CodeDomProvider class will be required. Currently there are Microsoft.CSharp.CSharpCodeProvider and Microsoft.VisualBasic.VBCodeProvider that can be used to generate C Sharp code and VisuaBasic.net code. Other programming languages don’t have CodeDomProvider yet, and might not have simple ways to represent some CodeDom constructions (delegates, enums, templates, and framework) due to difference in language specifications. However, creating a CodeDomProvider is not a very complex task, if the input CodeDom structure is restricted. Programmers can always build a CodeDomProvider for a particular language by inheriting from CodeDomProvider, and throw exceptions if the construction is too difficult to represent. create qr code