C# Namespace

A namespace is an organization construct. It helps us find and understand how a code base is arranged. Namespaces are not essential for C# programs. They are usually used to make code more understandable.

KeywordsNamespace keyword


Letters of the alphabet: ABC

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 directly use those types.

Also: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();

	    // Display types.

namespace A
    namespace B
	namespace C
	    public class CClass

namespace D
    public class DClass

namespace F
    public class FClass


Piece of computer software: a program

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.

Tip:Try changing namespace F into namespace F.F. Then modify the Main method to have the extra namespace as well.


Question and answer

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.

So:At the level of the intermediate language, the namespaces add no computational burden.

However:Namespaces will increase the size of the executable file and the metadata. This is not usually worth considering.


C# language

Conceptually, namespaces are an organizational construct that we use to formally change the way code is arranged.
Using namespaces,
we provide hints about ownership,
programmer responsibility
and intent.

Thus:A namespace provides an extra layer of information about the enclosed source text.

C#: Class