System.CodeDom Namespace
Provides classes that represent the structure of source code, enabling it to be processed and manipulated programmatically. This namespace is fundamental for code generation and compilation tasks.
Summary of Members
Represents a unit of code, such as a source file.
Represents a namespace declaration in code.
Represents a type declaration, such as a class, interface, or enum.
Represents a method member of a type.
Represents a field member of a type.
Represents a statement in code. This is an abstract base class.
Represents a reference to a type.
Represents a collection of compiler errors.
Example Usage
The following C# code snippet demonstrates how to create a simple class using the CodeDOM API.
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
public class CodeDomExample
{
public static void Main(string[] args)
{
// Create a CodeCompileUnit to hold the code.
CodeCompileUnit compileUnit = new CodeCompileUnit();
// Create a namespace.
CodeNamespace myNamespace = new CodeNamespace("MyGeneratedCode");
compileUnit.Namespaces.Add(myNamespace);
// Create a class declaration.
CodeTypeDeclaration myClass = new CodeTypeDeclaration("HelloWorld");
myClass.IsClass = true;
myNamespace.Types.Add(myClass);
// Create a method.
CodeMemberMethod myMethod = new CodeMemberMethod();
myMethod.Name = "SayHello";
myMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
myMethod.ReturnType = new CodeTypeReference(typeof(void));
// Add a statement to the method.
CodeMethodInvokeExpression invokeExpression = new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression("Console"),
"WriteLine",
new CodePrimitiveExpression("Hello, World!")
);
myMethod.Statements.Add(new CodeExpressionStatement(invokeExpression));
myClass.Members.Add(myMethod);
// Generate C# code.
CSharpCodeProvider provider = new CSharpCodeProvider();
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (System.IO.TextWriter writer = new System.IO.StringWriter(sb))
{
provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
}
Console.WriteLine("Generated C# Code:\n");
Console.WriteLine(sb.ToString());
}
}
This example constructs a `CodeCompileUnit` and populates it with a namespace, a class named `HelloWorld`, and a static method `SayHello` that prints "Hello, World!" to the console. Finally, it generates and prints the corresponding C# source code.