C# Namespaces with Examples

To define a namespace in C #, we use the keyword's namespace followed by a namespace and curly brackets that contain the namespace name, as follows:

Syntax:

namespace name
{
    //classes
    //methods
    //etc
}

Members are accessed by using the operator (.). The class in C # is known for its respective namespace.

Some Important Notes about namespace

  • In the same program, you can create two categories with the same name in two different namespaces.
  • No class can have the same name in a namespace.
  • In C #, the full class name begins with a namespace followed by the period operator (.) And the class name, known as the full class name.

Example:

using System;
namespace Entrypoint
{
    class Tech
    {
        public static void show()
        {
            Console.WriteLine("Shahzad Hussain");
        }
    }
}
class Tech1
{
    public static void Main(String[] args)
    {
        Entrypoint.Tech.show();
    }
}

Output:

Shahzad Hussain

Nested Namespaces

You can also specify a namespace in another namespace, which is called nested namespaces. To use members of a built-in namespace, the user must use the period (.) Operator.

Example:

using System;
namespace Entrypoint
{
    namespace NestedNamespace
    {
       class Tech
        {
            public Tech()
            {
                Console.WriteLine("Nested Namespace");
            }
        }
    }
}
class Tech1
{
	public static void Main(String[] args)
	{
	     new Entrypoint.nestednamespace.Tech();
	}
}

Output

Nested Namespace

The using keyword

In fact, it is impractical to call a function or class (or you can say members of their space) every time you use their full name. The example above is System.Console.WriteLine (“Shahzad Hussain”); a Entrypoint.Tech(); full name. Thus, C # provides a "using" keyword that helps the user not to re-enter their full names. The user only needs to specify the space name at the beginning of the program, then he can easily avoid using full names.

Example:

using System;
using Entrypoint;
namespace Entrypoint
{
    class Tech
    {
        public static void show()
        {
            Console.WriteLine("Shahzad Hussain");
        }
    }
}
class Tech1
{
    public static void Main(String[] args)
    {
        Tech.show();
    }
}

Output:

Shahzad Hussain