Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Generate .NET Code in Any Language Using CodeDOM

The CodeDOM namespace contains classes that abstract the idea of code. After defining code in this abstract manner, you can use a language-specific CodeProvider class to generate code in any .NET language from that single abstract CodeDOM representation.


advertisement
he .NET framework is replete with nooks and crannies of functionality that are amazingly powerful, but sorely underdocumented. One of those lesser-known capabilities lies in the CodeDOM namespace. This namespace is the .NET language equivalent of the HtmlTextWriter and XmlTextWriter classes, but rather than using the classes to write HTML or XML, you use the classes and methods in the CodeDOM namespace to write .NET code. One of the most interesting things about CodeDOM is that it's completely language-agnostic. The CodeDOM namespace abstracts most (not all—at least, not yet) types of code operations into an object model. You create object instances that represent namespaces, classes, fields, methods, properties, parameters, references to various types, and so forth.

Each .NET language has a special code provider class. For VB.NET, the code provider class is Microsoft.VisualBasic.VBCodeProvider. For C#, the class is Microsoft.CSharp.CSharpCodeProvider. Each provider gives you access to an object that implements the ICodeGenerator interface. The interface defines several GenerateCodeFrom... methods, one of which is GenerateCodeFromNamespace, which writes all the code for a namespace. Table 1 shows the high-level process to generate a namespace containing a class.

Table 1: The high-level process for generating a namespace containing a class with CodeDOM. You can refer to this process at any time by clicking the sidebar Generic CodeDOM Process.


1.

Create a namespace.



2.

Import namespaces, such as System.Text or System.Drawing.

3.

Create a class and add it to the namespace.

4.

Create member fields for the class, defining the name and type for each field.

5.

Create methods and properties

6.

Populate each method or property with code by adding statements to it.

7.

Add the method or property to the class.

8.

Create an appropriate code provider object.

9.

Use the code provider's CreateGenerator method to obtain a CodeGenerator object.

10.

Call one of the generator's GenerateCodeFrom... methods to emit the code.


The CodeDOM namespace has a large number of classes, which can be a little intimidating at first. The best way to learn them is to dive in and create a class.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap