CodeCompileUnit Class
Represents the root element of a namespace or code source file. A CodeCompileUnit
can contain one or more CodeNamespace
objects and CodeDirective
objects.
Namespace: System.CodeDom
Assembly: System (in System.dll)
public class CodeCompileUnit : System.CodeDom.Compiler.CodeParser, System.Runtime.Serialization.ISerializable
Constructors
public CodeCompileUnit()
Initializes a new instance of the CodeCompileUnit class.
Properties
public CodeAttributeArgumentCollection Attributes { get; set; }
Gets or sets a collection of attributes for the code element.
public CodeDirectiveCollection CompileDirectives { get; }
Gets a collection of compiler directives for the code compile unit.
public CodeNamespaceCollection Namespaces { get; }
Gets a collection of namespaces for the code compile unit.
Methods
protected virtual void OnDeserialization(object sender)
Called by the deserializer when deserialization is complete.
public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
Populates a SerializationInfo object with the data required to serialize the CodeCompileUnit object.
Remarks
A CodeCompileUnit
is the highest-level element in the System.CodeDom
object model. It represents the entire source code for a compilation unit, which can be a single source file or a set of files.
It typically contains one or more CodeNamespace
objects, which group related types, and can also contain CodeDirective
objects, such as `#region` and `#endregion` directives.
Example
The following example demonstrates how to create a CodeCompileUnit
and add a namespace to it.
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
public class Example
{
public static void Main()
{
// Create a CodeCompileUnit
CodeCompileUnit compileUnit = new CodeCompileUnit();
// Create a CodeNamespace
CodeNamespace myNamespace = new CodeNamespace("MyCompany.Utilities");
// Add the namespace to the compile unit
compileUnit.Namespaces.Add(myNamespace);
// Add a type to the namespace (for demonstration)
CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyHelperClass");
myClass.IsClass = true;
myNamespace.Types.Add(myClass);
// You can then use a CodeGenerator to output this to a file
// or a string.
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
System.IO.StringWriter writer = new System.IO.StringWriter();
provider.GenerateCodeFromCompileUnit(compileUnit, writer, null);
Console.WriteLine(writer.ToString());
}
}