CodeCompileUnit.Namespaces Property


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Gets the collection of namespaces.

Namespace:   System.CodeDom
Assembly:  System (in System.dll)

public CodeNamespaceCollection Namespaces { get; }

Property Value

Type: System.CodeDom.CodeNamespaceCollection

A CodeNamespaceCollection that indicates the namespaces that the compile unit uses.

You can add and remove CodeNamespace objects from this collection. Each object represents a namespace.


Some languages support only a single namespace that contains a single class in a compile unit.

The following code example constructs a CodeCompileUnit that models the program structure of a simple "Hello World" program. This example is part of a larger example that also produces code from this model, and is provided for the CodeDomProvider class.

// Build a Hello World program graph using 
// System.CodeDom types.
public static CodeCompileUnit BuildHelloWorldGraph()
    // Create a new CodeCompileUnit to contain 
    // the program graph.
    CodeCompileUnit compileUnit = new CodeCompileUnit();

    // Declare a new namespace called Samples.
    CodeNamespace samples = new CodeNamespace("Samples");
    // Add the new namespace to the compile unit.

    // Add the new namespace import for the System namespace.
    samples.Imports.Add(new CodeNamespaceImport("System"));

    // Declare a new type called Class1.
    CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");
    // Add the new type to the namespace type collection.

    // Declare a new code entry point method.
    CodeEntryPointMethod start = new CodeEntryPointMethod();

    // Create a type reference for the System.Console class.
    CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console");

    // Build a Console.WriteLine statement.
    CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(
        csSystemConsoleType, "WriteLine",
        new CodePrimitiveExpression("Hello World!"));

    // Add the WriteLine call to the statement collection.

    // Build another Console.WriteLine statement.
    CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression(
        csSystemConsoleType, "WriteLine",
        new CodePrimitiveExpression("Press the Enter key to continue."));

    // Add the WriteLine call to the statement collection.

    // Build a call to System.Console.ReadLine.
    CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression(
        csSystemConsoleType, "ReadLine");

    // Add the ReadLine statement.

    // Add the code entry point method to
    // the Members collection of the type.

    return compileUnit;

.NET Framework
Available since 1.1
Return to top