A namespace is a logical unit of organization. There are namespaces that are built in to the .NET Framework, and ones you can make yourself.
The .NET Framework classes are organized in namespaces. For example, the common method of writing to the console window is with Console.WriteLine("");.
Console.WriteLine("Message");
Using Console.WriteLine(""); requires a using directive at the top of the file to indicate the namespace System.
using System;
Without the using directive we would write the fully qualified name.
System.Console.WriteLine("Message");
Most C# applications begin with a section of using directives. This section lists the namespaces that the application will be using frequently, and saves the programmer from specifying a fully qualified name every time that a method that is contained within is used. [MSDN]
You can also declare your own namespaces. These can help provide context, or contain the scope of class and method names.
In the example below you can see that there are three different uses of the same term, Orange, and that each is used in a different context. If we tried to define multiple classes with the same name in the same namespace there would be confusion over which class we were referring to.
- The variety of this orange is Valencia.
- Orange is in the region of France named Provence-Alpes-Cote d'Azur.
- #FF7F00 is a hexadecimal code for an orange color.
C# Namespaces Example Code
Try it out! Start a new project in Visual Studio and replace what Visual Studio generated with the code below. Save it and run it (Using the Start button in Visual Studio or the F5 key on your keyboard).
using System; namespace namespacesExample { class Program { static void Main() { Console.WriteLine("If I want to use the word Orange for different meanings, "); Console.WriteLine("I can define them in different namespaces. "); Console.WriteLine("Fruit.Orange.Genus: " + Fruit.Orange.Genus); Console.WriteLine("Place.Orange.Country: " + Place.Orange.Country); Console.WriteLine("Color.Orange.Hexadecimal: " + Color.Orange.Hexadecimal); Console.ReadKey(); } } } namespace Fruit { class Orange { //default values public static string Genus = "Citrus sinensis"; public static string Variety = "Valencia"; public static string Grade = "US Fancy"; } } namespace Place { class Orange { //default values public static string Country = "France"; public static string Region = "Provence-Alpes-Cote d'Azur"; public static int Population = 30025; } } namespace Color { class Orange { public static string Hexadecimal = "#FF7F00"; } }