Using Namespaces
The example you have seen so far is a very small program. However, small programs can soon grow into bigger programs. As a program grows, it creates two problems. First, more code is harder to understand and maintain than less code. Second, more code usually means more names; more named data, more named
In the past, programmers tried to solve the
Namespaces help solve this problem by creating a named container for other identifiers, such as classes. Two classes with the same name will not be
namespace TextHello { class Greeting { ... } }
You can then refer to the
Greeting
class as
TextHello.Greeting
in your own programs. If someone else also creates a
Greeting
class in a different namespace and
It is good practice to define all your classes in namespaces, and the Visual Studio 2005 environment
Of course, if you had to write the fully qualified name of a class every time, it would be no better that just naming the class SystemConsole . Fortunately, you can solve this problem with a using directive. If you return to the TextHello program in Visual Studio 2005 and look at the file Program.cs in the Code and Text Editor window, you will notice the following statements:
using System; using System.Collections.Generic; using System.Text;
The
using
statement
The following exercise
Try longhand names
In the Code And Text Editor window, comment out the using directive at the top of Program.cs:
//using System;
On the Build menu, click Build Solution. The build fails, and the Output pane displays the following error message twice (once for each use of the Console class):
The name 'Console' does not exist in the current context.
In the Output pane, double-click the error message. The identifier that caused the error is selected in the Program.cs source file.
TIP
The first error can affect the reliability of
In the Code and Text Editor window, edit the Main method to use the fully qualified name System.Console .
Main should look like this:
static void Main(string[] args) { System.Console.WriteLine("Hello World"); }
NOTE
When you type
System.
, notice how the names of all the items in the
System
namespace are displayed by IntelliSense.
On the Build menu, click Build Solution. The build succeeds this time. If it doesn't, make sure
Main
is
exactly
as it appears in the
Run the application to make sure it still works by clicking Start Without Debugging on the Debug menu.
In the Solution Explorer, click the + to the left of the References entry. This displays the assemblies referenced by the Solution Explorer. An assembly is a library containing code written by other developers (such as the .NET Framework). In some cases, the classes in a namespace are stored in an assembly that has the same name (such as
System
), although this does not have to be the case—some assemblies hold more than one namespace. Whenever you use a namespace, you also need to make sure that you have referenced the assembly that contains the classes for that namespace;