C# Namespace

Namespaces

Declaring your own namespaces can help you control the scope of class and method names in larger programming projects. Namespaces have the following properties:

  • They organize large code projects.

  • They're delimited by using the . operator.

  • The using directive avoids the requirement to specify the name of the namespace for every class.

Use the namespace keyword to declare a namespace, as in the following example:

namespace SampleNamespace
{
    class SampleClass
    {
        public void SampleMethod()
        {
            System.Console.WriteLine(
                "SampleMethod inside SampleNamespace");
        }
    }
}

The name of the namespace must be a valid C# identifier name.

File scoped namespace

Beginning with C# 10, you can declare a namespace for all types defined in that file, as shown in the following example:

namespace SampleNamespace;

class SampleClass
{
    public void SampleMethod()
    {
        System.Console.WriteLine("SampleMethod");
    }
}

The advantage of this new syntax is that it's simpler, saving horizontal space and braces. That makes your code easier to read.

Same code can be written as:

namespace SampleNamespace;

class SampleClass
{
    public void SampleMethod()
    {
        System.Console.WriteLine("SampleMethod");
    }
}

Limitation of file scoped namespace

File scoped namespaces can't include additional namespace declarations. You cannot declare a nested namespace or a second file-scoped namespace:

namespace SampleNamespace;

class AnotherSampleClass
{
    public void AnotherSampleMethod()
    {
        System.Console.WriteLine(
            "SampleMethod inside SampleNamespace");
    }
}

namespace AnotherNamespace; // Neither this is allowed...

namespace ANestedNamespace // Nor this!
{
   // declarations...
}

Last updated