C# Namespace

  • The namespace keyword is used to organize classes and other relevant items together, provide them the unique access globally and control the scope of them.
  • C# namespace is implicitly defined as public access level.
  • If no namespace is declared explicitly, a default namespace will be added by the compiler.

The format of the example to declare a namespace is shown as follows.

namespace A
{
    public class B
    {
        public static void C()
        {
		// Code here
        }
    }
}

You can use the code below to access the method C in other programs.

A.B.C();

Example 01-65-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
namespace A
{
    public class B
    {
        public static void C()
        {
            System.Console.WriteLine("Method C in the class B of namespace A.");
        }
    }
}

namespace D
{
    using System;

    class E
    {
        public static void Main()
        {
            A.B.C();
            Console.Read();
        }
    }  
}

Output

Method C in the class B of namespace A.

Explanation

  • Line 1-10: Declare a namespace A and a static method C() in class B.
  • Line 7: System is a namespace. Console is a class in System and WriteLine is a static method of class Console. You call the method by the format of [namespace].[Class].[Method].
  • Line 12-24: Declare another namespace D to test how to access the method C().
  • Line 14: Indicate the classes in System can be used without System explicitly.
  • Line 20: Call the method with full path.
  • Line 21: Unlike line 7, System can be omitted here because of "using" statement in line 14.

Namespaces are mostly used like folders. We can put sub folders and files in a folder. Also we can create nested namespaces in a namespace.

Nested Namespace

To add a nested namespace, the example Example 01-65-01 was changed to the following.

Example 01-65-02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace A
{
    namespace D
    {
        public class B
        {
            public static void C()
            {
                System.Console.WriteLine("Method C in class B of namespace A.D");
            }
        }
    }

    class E
    {
        public static void Main()
        {
            A.D.B.C();      // A. can be omitted.
            System.Console.Read();
        }
    }
}

Output

Method C in class B of namespace A.D

Explanation

  • Line 1-22: Declare a namespace A including everything in the program.
  • Line 3-12: Declare a nested namespace D and put the class B and method C in the namespace.
  • Line 14-21: Define a class E in namespace A.
  • Line 18: Call the method with full path. Pay attention, "A" can be omitted because the caller is also in the same namespace of the calling method.
  • Line 19: System must be written here because no using statement is used.