C# FAQ 1.4 - How Do I Work with Namespaces?
As explained in FAQ 1.1, namespaces are placed at the top of the .NET hierarchy. Namespaces are nothing but groups of classes. Classes are also called types or assemblies. Each of the classes in a namespace can contain lots of methods.
Basically, namespaces are treated as containers for all classes. Namespaces are classified into several categories, based on the functionality of their classes. For example, if you need to work with databases, you have to call the System.Data namespace. Similarly, if you work with files, you have to call the System.IO namespace.
Namespaces in C# are similar to packages in Java, where we use a statement such as java.sql.*. Moreover, all C# programs should call the System namespace. This is the root of all other namespaces in the .NET Framework.
You have to apply the namespaces by following certain conventions as laid out by the .NET Framework. All namespaces should be called in your programs by applying the using keyword. For example, to call the System namespace, you have to use a statement as shown in Listing 1.4.1:
Notice the semicolon at the end of the statement. It is required for all statementsin C#.
Note - You should also be aware that C# is a case-sensitive language, like Java.
You should not call classes with the using keyword. Hence, the code in Listing 1.4.2 results in a compilation error because Console is a class:
// compilation error using System.Console;
Because the term Console is one of the classes located in the System namespace, you apply it along with its built-in methods. For example, you can write text to the command prompt by using the WriteLine() method of the Console class, as shown in Listing 1.4.3.
Even though you cannot directly apply the class names along with the using directive, you can create an alias, as shown in Listing 1.4.4:
using mydotnet = System.Console;
After that, you have to apply the alias name, mydotnet, in your C# program, as shown in Listing 1.4.5:
You can however completely omit the namespace declaration (With the using keyword) in a C# program. But as an alternative you can refer the namespace name in the beginning of the relevant line of each statement as shown in listing 1.4.6:
System.Console.WriteLine("Welcome to C#");
A list of .NET namespaces is shown in the following table:
About the AuthorAnand Narayanaswamy, a Microsoft Most Valuable Professional in Visual C#, works as an independent consultant and technical writer based in Trivandrum, India. He has contributed numerous articles on various topics relating to C# and ASP.NET for developer.com and Codeguru.com. Anand specializes in C#, ASP.NET, Visual Basic .NET, ASP, Visual Basic 6.0, and in the development of courseware, technical articles, documentation, and reviews of products and books.
Last Updated: 2/5/2004
# # #