Namespaces are program elements designed to help us organize
our programs. They also provide assistance in avoiding name clashes between two
sets of code. Implementing Namespaces in our own code is a good habit because
it is likely to save us from problems later when we want to reuse some of our
code. For example, if we create a class named Console, we would need to put it
in our own namespace to ensure that there wasn't any confusion about when the System.Console class should be used or when our class
should be used.
Example
// Namespace Declaration
using System;
namespace newnamespace
{
// Program start class
class
space
{
public static void Main()
{
// Write to console
Console.WriteLine("This is the new
Namespace.");
}
}
}
In the example above we have declared the new namespace by putting the word namespace in front of newnamespace.
Curly braces surround the members inside the newnamespace namespace.
Nested Namespace
// Namespace Declaration
using System;
namespace newnamespace
{
namespace first
{
class
space
{
public static void
Main()
{
// Write to console
Console.WriteLine("This is the new first
Namespace.");
}
}
}
}
Namespaces allow us to create a system to organize
our code. A good way to organize our namespaces is via a hierarchical
system. We put the more general names at the top of the hierarchy and get more
specific as we go down. This hierarchical system can be represented by nested namespaces.
The code above shows how to create a nested namespace.