Share via


namespace (C# Reference) 

The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types. For complete syntax information, see the C# Language Specification.

namespace name[.name1] ...] {
      type-declarations
}

Parameters

  • name, name1
    A namespace name can be any legal identifier. A namespace name can contain periods.

Remarks

Even if you do not explicitly declare one, a default namespace is created. This unnamed namespace, sometimes called the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace.

Namespaces implicitly have public access and this is not modifiable. For a discussion of the access modifiers you can assign to elements within a namespace, see Access Modifiers (C# Reference).

It is possible to define a namespace in two or more declarations. For example, the following sample defines two classes as part of the MyCompany namespace:

// cs_namespace_keyword.cs
// compile with: /target:library
namespace MyCompany.Proj1 
{
    class MyClass 
    {
    }
}

namespace MyCompany.Proj1 
{
    class MyClass1 
    {
    }
}

Example

The following example shows how to call a static method in a nested namespace.

// cs_namespace_keyword_2.cs
using System;
namespace SomeNameSpace
{
    public class MyClass 
    {
        static void Main() 
        {
            Nested.NestedNameSpaceClass.SayHello();
        }
    }

    // a nested namespace
    namespace Nested   
    {
        public class NestedNameSpaceClass 
        {
            public static void SayHello() 
            {
                Console.WriteLine("Hello");
            }
        }
    }
}

Output

Hello

For More Information

For more information on using namespaces, see the following topics:

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 3.4.1 Namespace members

  • 3.8 Namespace and type names

  • 9 Namespaces

See Also

Reference

C# Keywords
Namespace Keywords (C# Reference)
using (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference