C# Namespace Examples

A namespace is an organization construct. It helps you find and understand how your code base is arranged. Namespaces are not essential for C# programs. They are usually used to improve the code's understandability. They can be nested and also included with the using directive.

KeywordsNamespace keyword

Examples

Note

This example has namespaces with the identifiers A, B, C, D, E, and F. Namespaces B and C are nested inside namespace A. Namespaces D, E, and F are all at the top level of the compilation unit. In the Program class, notice how the Main entry point uses the CClass, DClass, and FClass types. Because the using A.B.C and using D directives are present in namespace E, the Main method can use those types directly. With FClass, the namespace must be specified explicitly because F is not included inside of E with a using directive.

Program that demonstrates namespace use [C#]

using System;
using A.B.C;

namespace E
{
    using D;

    class Program
    {
	static void Main()
	{
	    // Can access CClass type directly from A.B.C.
	    CClass var1 = new CClass();

	    // Can access DClass type from D.
	    DClass var2 = new DClass();

	    // Must explicitely specify F namespace.
	    F.FClass var3 = new F.FClass();

	    // Output.
	    Console.WriteLine(var1);
	    Console.WriteLine(var2);
	    Console.WriteLine(var3);
	}
    }
}

namespace A
{
    namespace B
    {
	namespace C
	{
	    public class CClass
	    {
	    }
	}
    }
}

namespace D
{
    public class DClass
    {
    }
}

namespace F
{
    public class FClass
    {
    }
}

Output

A.B.C.CClass
D.DClass
F.FClass

Allowed namespace type names. In addition to using the normal alphanumeric names for namespaces, you can include the period separator in a namespace. This is a condensed version of having nested namespaces. Try changing namespace F into namespace F.F; then modify the Main method to have the extra namespace as well.

Runtime

Question and answer

So what effect do namespaces have on the execution of your code? There is no performance impact because namespaces do not add complexity to the code itself, just to how it is organized in the source files. At the level of the intermediate language, the namespaces do not add any computational burden. However, namespaces will increase the size of the executable file and the metadata; this is not usually worth considering.

Summary

The C# programming language

Conceptually, namespaces are an organizational construct that you can use to formally change the way your code is arranged. Using namespaces, you can provide hints about legal ownership, programmer responsibility, and even how the code is to be used. Namespace can in these ways provide an extra layer of contextual information about the enclosed source text.

Class Examples
.NET