Component Model
  Use the CodeDOM

Get URL for this page

How Do I...Use the CodeDOM to emit source code?

What is the CodeDOM
The CodeDOM is an API that gives you the ability to create a programming structure of namespaces, objects, and programming constructs by adding items to different collections. All CodeDOM programs start out with the creation of a ICodeGenerator for the target language. The following code shows the creation of the ICodeGenerator for C#.


Dim cg As ICodeGenerator = New CSharpCodeProvider().CreateGenerator()
 ...
Dim cdp As New CSharpCodeProvider()
cg = cdp.CreateGenerator()
VB

The ICodeGenerator is used to generate the actual code once a CodeDOM tree is built. To begin building your tree, you need to start with a CodeNamespace object. This object will contain any types and import directives. With the CodeNamespace object you can begin the tree. For the following sample, several CodeNamespaceImport objects are used to generate import directives for commonly used namespaces. The sample also needs to generate a class construct so by using a CodeTypeDeclaration and setting the IsClass property to true. The following code demonstrates these concepts.


Dim cnamespace As New CodeNamespace("Microsoft.Samples")
cnamespace.Imports.Add(New CodeNamespaceImport("System"))
 ...
Dim co As New CodeTypeDeclaration(typeName + "List")
co.IsClass = true
cnamespace.Types.Add (co)
VB

At the end of the previous example, the class type definition is added to the Types collection of the CodeNamespace object. This is how a CodeDOM tree is built. Starting with a CodeNamespace object and working down through classes to class members. Class members in turn contain different types of code statements and expressions. Once the entire tree is built, the entire source tree can be written with a call to GenerateCodeFromNamespace, a method on ICodeGenerator. The method is being passed the CodeNamespace object and a TextWriter.


baseCompiler.GenerateCodeFromNamespace (cnamespace, w, Nothing)
VB

The following sample demonstrates the techniques described above by generating the code for a strongly typed List. It also contains additional information and code for generating code statements and expressions that were left out of the above documentation for brevity.

Example

 
VB ListBuilder.exe

[Run Sample] | [View Source]


Copyright 2001-2002 Microsoft Corporation. All rights reserved.