Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Namespaces—The First Contact

Namespaces are a fundamental concept of C# and .NET. In this section, we take our first look at namespaces and Mono in general.

Fundamentals

Namespaces can be compared with packages. Some of you already know this concept from languages such as Sun's Java. However, there are some fundamental differences that must be discussed: Namespaces are a logical structure—not every namespace has to be in a separate file. The physical organization of files has nothing to do with logical structures. The advantage is that it's no problem to use modules from different vendors without worrying about conflicts between those modules. If namespaces are used properly, conflicts are very unlikely.

To make it short: Namespaces help us to define logical units consisting of classes, variables, and methods.

One of the most important namespaces of Mono and .NET is the System namespace. It contains a set of basic and fundamental classes that you'll need for almost any application based on Mono. If we look at the method called WriteLine, we'll see that it is part of the Console object. As you might expect, this object is part of the System namespace just as many other objects are.

Namespaces can be nested. That means that a namespace can consist of various other namespaces. A good example is the System.Collection namespace. You'll need the System.Collection namespace to manage dynamic data structures.

Using Namespaces

Thinking of namespaces leads to one rudimentary question: When should you define a namespace? Well, the basic idea is relatively simple: Whenever you want to group a set of classes logically, namespaces can make sense. In addition, namespaces make sense when you want to implement an entire software package because it helps you to separate your classes from those of other people. Your product can contain classes that fulfill a certain task—the classes of your business rival will do the same thing. If you use your company's name as the name of your namespace, it's very likely that your software components can coexist with other people's software. If you use namespaces cleverly, you can avoid many nasty problems.

  • + Share This
  • 🔖 Save To Your Account