C# Namespaces Tutorial For Beginners With Examples

Namespaces are used to group set of related types and hence helps in organizing the code.
Types with same names can exist within different namespaces to create globally unique types.

Creating a Namespace

A namespace is created by using the keyword namespace followed by the namespace name. Below example shows the usage of namespace in a C# program.
    namespace HelloWorld
    {  
        class Employee
        {           
            void Employee()
            {

            }
        }
    }
        

Contents of a namespace

In C#, a namespace can have the following types within it:

Using a Namespace

An using directive is used to allow the types inside a particular namespace to be used in a program.
  using HelloWorld;
        
An using directive can also be used to create alias for a namespace or type.
  using SpecialCollections = System.Collections.Specialized;
        
Aliases can be used instead of writing the fully qualified names.
    namespace Calculations
    {  
        public class Compute
        {
            SpecialCollections.StringDictionary stringDictionaryObject;

            void Compute()
            {

            }
        }
    }
        

Nested Namespaces

Like types, namespaces can also be nested.
    namespace Person
    {
        namespace Programmer
        {
            public class VB
            {

            }

            public class csharp
            {

            }
        }

        public class Employee
        {
            void Employee()
            {

            }    
        }
    }
        
Dot (.) Operator is used to access nested namespaces and types.
  Person.Programmer.VB vbProgrammer = new Person.Programmer.VB();