Namespaces
Namespaces are C# program elements designed to help you organize your programs. They also provide assistance in avoiding name clashes between two sets of code. Implementing Namespaces in your own code is a good habit because it is likely to save you from problems later when you want to reuse some of your code. For example, if you created a class named Console, you would need to put it in your own namespace to ensure that there wasn't any confusion about when the System.Console class should be used or when your class should be used. Generally, it would be a bad idea to create a class named Console, but in many cases your classes will be named the same as classes in either the .NET Framework Class Library or a third party library and namespaces help you avoid the problems that identical class names would cause.
Namespaces don't correspond to file or directory names. If naming directories and files to correspond to namespaces helps you organize your code, then you may do so, but it is not required.
Listing 6-1. The C# Namespace: NamespaceCSS.cs
// Namespace Declaration
using System;
// The C# Namespace
namespace csharp_
{ // Program start class class NamespaceCSS
{ // Main begins program execution. public static void Main()
{ // Write to console Console.WriteLine("This is the new C# Station Namespace.");
}
}
}
using System;
// The C# Namespace
namespace csharp_
{ // Program start class class NamespaceCSS
{ // Main begins program execution. public static void Main()
{ // Write to console Console.WriteLine("This is the new C# Station Namespace.");
}
}
}
Listing 6-1 shows how to create a namespace. We declare the new namespace by putting the word namespace in front of csharp_station. Curly braces surround the members inside the csharp_station namespace.
Listing 6-2. Nested Namespace 1: NestedNamespace1.cs
// Namespace Declarationusing System;
// The C# Tutorial Namespacenamespace csharp_
{ namespace tutorial
{ // Program start class class NamespaceCSS
{ // Main begins program execution. public static void Main()
{ // Write to console Console.WriteLine("This is the new C# Station Tutorial Namespace.");
}
}
}
}
// The C# Tutorial Namespacenamespace csharp_
{ namespace tutorial
{ // Program start class class NamespaceCSS
{ // Main begins program execution. public static void Main()
{ // Write to console Console.WriteLine("This is the new C# Station Tutorial Namespace.");
}
}
}
}
Namespaces allow you to create a system to organize your code. A good way to organize your namespaces is via a hierarchical system. You put the more general names at the top of the hierarchy and get more specific as you go down. This hierarchical system can be represented by nested namespaces. Listing 6-2 shows how to create a nested namespace. By placing code in different sub-namespaces, you can keep your code organized.
No comments:
Post a Comment