Namespaces

Namespaces are means of organizing classes and controlling scope in C#.

In the following example, System is a namespace, and Console is a class of System:

System.Console.WriteLine("Hi Universe!");

If the using keyword with a namespace name appears at the beginning of the application, the namespace name can be omitted from the code.

Console.WriteLine("Hi Universe");

Declaring a namespace allows for the control of class scope and method scope within large applications. The syntax for a namespace follows:

namespace TheNamespace
{
	class AClass
	{
		public void AMethod()
		{
			System.Console.WriteLine("Stuff");
		}
	}
}

NAMESPACE ALIAS

An alias can be created for a namespace. Review an alias example below:

using OrgProject = Organization.Project.Nested;

Namespace aliases serve the following purposes:

  1. Disambiguation – Aliases make the namespace in use clearer in code.
  2. Managing conflicting extension methods – If conflicts exist between namespaces, an alias provides a workaround for access; for example, a namespace preventing the visibility of another.
  3. Avoiding repeated use of long object names – Some methods and objects may require a verbose reference. An alias dramatically reduces this and the overall LOC within an application.

NAMING

The name of a namespace comes from its structure. The order of its name specifies its hierarchy; for example. X.Y suggests X as the namespace, and Y as a nested element. Review namespace syntax below and the associated name:

namespace Name // Name
{
	class ClassName // Name.ClassName
	{
		class NestedClassName // Name.ClassName.NestedClassName
		{
		}
	}
	namespace NameTwo // Name.NameTwo
	{
		class ClassNameTwo // Name.NameTwo.ClassNameTwo
		{
		}
	}
}

MEMBERS

Every namespace has associated members. These members consist of the namespaces and types declared within the namespace, and they have no restrictions; they are always public. The members of the namespace follow:

  1. Struct members
  2. Enumeration members
  3. Class members
  4. Interface members
  5. Array members
  6. Delegate members