Defining Your Own Namespaces

   


The syntax for defining a namespace of your own making is straightforward. Simply write the keyword namespace followed by a namespace name you've chosen. Below this header, include a pair of curly braces; they delimit the scope of your namespace. You can then include the classes you want this namespace to contain by writing their definitions between these curly braces. The source code of Listing 15.1 for example, defines a namespace called ElevatorSimulation that contains an Elevator and a Person class. The scope of the ElevatorSimulation namespace spans from line 2 to line 36.

Listing 15.1 Defining the ElevatorSimulation namespace
01: namespace ElevatorSimulation 02: { 03:     using System; 04: 05:     class Elevator 06:     {             <Class_members> 20:     } 21: 22:     class Person 23:     {             <Class_members> 35:     } 36: } 

Note: For space reasons the class members of the Elevator and Person classes have not been included. This explains the gaps in the line numbering. Line numbers 20 and 35 have been chosen somewhat arbitrarily. This listing does not compile.

Tip

graphics/bulb.gif

Pascal casing is, per convention, used for namespace names.


The Source File Constitutes a Compilation Unit

graphics/common.gif

The C# source code you write with Notepad (or another editor) becomes a C# source file when it is saved with the .cs extension. Each source file constitutes a compilation unit. So far, we have written programs consisting of just one compilation unit, but a program can consist of two or more compilation units. Later, we will see how this is made possible by the compiler.


You can define an unlimited number of namespaces in one compilation unit. The ways by which they can be arranged are numerous, but they are all based on a couple of simple rules:

  • Zero or more namespaces can be positioned beside each other in a compilation unit.

  • Zero or more namespaces can be positioned beside each other inside another namespace.

So, not only can namespaces be written next to each other in the compilation unit or inside another namespace, they can also be nested inside each other to any depth you might require. In a moment, we will see examples of the different overall structures.


   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net