RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


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.

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.


Create a namespace.


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


Create a class and add it to the namespace.


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


Create methods and properties


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


Add the method or property to the class.


Create an appropriate code provider object.


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


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.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date