Home   |   QuickStart Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   
  |   I want my samples in...      

How Do I...? Common Tasks QuickStart Tutorial

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#.

		
ICodeGenerator cg =new CSharpCodeProvider().CreateGenerator();
 ...
CSharpCodeProvider cdp = new CSharpCodeProvider();
cg = cdp.CreateGenerator();
C#


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.

		
CodeNamespace cnamespace = new CodeNamespace("Microsoft.Samples");
cnamespace.Imports.Add (new CodeNamespaceImport ("System") );
 ...
CodeTypeDeclaration co = new CodeTypeDeclaration (typeName +"List");
co.IsClass = true;
cnamespace.Types.Add (co);
C#


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, null);
C#


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
View Source
[This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\CompMod\CodeDom\ListBuilder\]



Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.