Console Application – Namespaces



C# Namespaces – Console Application

The namespaces helps to organize a programs. A namespace is designed for providing way to keep set of classes in a one organization. Namespace avoiding a clash of class by declaring same class name declared in another namespace.

Declaring Namespace :

A namespace definition starts with keyword namespace followed by the namespace name as like below:

namespace namespace_example
{
//programming code declaration
}

How namespace will helps:
For example in c# console application program, if we created same class name which is already available in .net framework class library, so there is a same class name clash problem occurs, but the namespace helps to avoid this kind of same declaration class name problem.

namespace MyFirstConsoleApp
{
class Program
{
static void Main(string[] args)
{
//code
}
}
}

In above example we defined namespace MyFirstConsoleApp with one class Program and a static function Main.

Here, we understand the same class name problem with an example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace first_example
{
class first
{
public void firstfunction()
{
Console.WriteLine("The first namespacce example");
}
}
}
namespace Second_example
{
class first
{
public void firstfunction()
{
Console.WriteLine("The second namespacce example");
}
}
}

namespace MyExample
{
class Program
{
static void Main(string[] args)
{
first_example.first fst = new first_example.first();
fst.firstfunction();

Second_example.first sec = new Second_example.first();
sec.firstfunction();

Console.Read();
}
}
}

The output of above namespace example is:

namespace in c# console application.
namespace in c# console application.

 


Nested Namespaces :

If we define one namespace inside the other namespace known as nested namespace.
Let’s take an example of nested namespace to understand more..

C# Nested Namespace Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace first_example
{
class first
{
public void firstfunction()
{
Console.WriteLine("The first namespacce example");
}
}

namespace Second_example
{
class first
{
public void firstfunction()
{
Console.WriteLine("The second namespacce example");
}
}
}
}
namespace MyExample
{
class Program
{
static void Main(string[] args)
{
first_example.first fst = new first_example.first();
fst.firstfunction();

first_example.Second_example.first sec = new first_example.Second_example.first();
sec.firstfunction();

Console.Read();
}
}
}

The output of  above nested namespace example is:

namespace in c# console application.
namespace in c# console application.

Leave a Reply

Your email address will not be published. Required fields are marked *