LogIn
I don't have account.

Namespace in C#

Code Crafter

207 Views

A namespace is a collection of classes, interfaces, structs, enums and delegates. namespace can be nested that means one namespace can contain other namespaces. Namespace is used to organize code into logical groups and to prevent name collisions i.e. a class names declared in one namespace does not conflict with the same class names declared in another.

Declaration Of Namespace

In c#, we write namespace by using namespace keyword

namespace <namespace_name>
{
    //Namespace
    //Classes
    //Interfaces
    //Structures
    //Delegates
}

Name of namespace can be any valid C# identifier or combinations of identifiers separated by ".".

Example :-
namespace NSP1.NSP2
{
    class A {}
    class B {}
}
namespace NSP1
{
    namespace NSP2
    {
        class A {}
        class B {}
    }
}
namespace NSP1.NSP2
{
    class A {}
}
namespace NSP1.NSP2
{
    class B {}
}
All above declarations are semantically equivalent.
Accessing Namespace Members
You can access the members of namespace in two ways.

1. Fully Qualified Names

2. Using Keyword

Fully Qualified Names(FQN)
<namespace_name>.<member_name>
class Program
{
    public static void Main()
    {
        var objA = new NSP1.NSP2.A();
    }
}
Using Keyword

Using fully qualified name is a time consuming process for developer.C# provides a keyword “using” which help the developer to avoid writing FQN again and again.while writing the code developer just refer the classes.During compile time, the compiler will map all the classes with fully qualified name of the class. Once the fully qualified name has been found, it is used to convert the code to Intermediate language code.

Intermediate language code :All classes, interfaces, enums and delegates are referenced with their fully qualified name.

using <namespace_name>;
using NSP1.NSP2;
namespace NSP
{
    class Program
    {
        public static void Main()
        {
            var objA = new A();
        }
    }
}

Note :- You can use the keyword "using" inside C# namespace.

namespace NSP
{
    using NSP1.NSP2;
    class Program
    {
        public static void Main()
        {
            var objA = new A();
        }
    }
}
Important Points :-

Access modifiers/specifiers of namespace in c# is not modifiable. it is implicitly have public access.

It is not possible to use any access modifiers like private, protected, public etc with a namespace declarations.

The default access modifiers of namespace element is internal.

The access modifiers of namespace elements can't be explicitly declared as private or protected.

The namespace allows only public and internal elements as it members.

Inside a namespace, two classes cann't have the same name.