Home > Articles > Software Development & Management > Object Technology

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

Creating Namespaces

The last OOP topic we'll look at in this chapter is how to create your own namespaces. As you know, namespaces let you divide programs up to avoid clashes between identifiers (even if you don't declare your own namespace, your code is given its own default namespace, the global namespace). To create your own namespace, you use the namespace keyword:

namespace name[.name1] ...] {
 type-declarations
}

Here are the parts of this statement:

  • name, name1—A namespace name can be any legal identifier, and it can include periods.

  • type-declarations—Within a namespace, you can declare one or more of the following types: another namespace, a class, interface, struct, enum, or delegate.

You can create as many namespaces in a file as you want; just enclose the code for each namespace in the code block following the namespace keyword. For example, here's how we can put the Messager class into the namespace Output:

namespace Output
{
 class Messager
 {
  public string message = "Default message.";

  public void DisplayMessage()
  {
   System.Console.WriteLine(message);
  }
 }
}

To access Messager outside the Output namespace, you qualify its name as Output.Messsager, just as you can qualify Console.Writeline as System. Console.WriteLine. (Alternatively, you can use a using Output directive, just as you use a using System directive.) You can see this at work in ch03_15.cs, Listing 3.15.

Naming Namespaces

Microsoft's suggestion is to name namespaces this way: CompanyName.ProjectName.Component. SubComponent.

Listing 3.15 Namespace Example (ch03_15.cs)

class ch03_15
{
 public static void Main() 
 {
  Output.Messager obj = new Output.Messager();
  obj.message = "Hello from C#.";
  obj.DisplayMessage();
 }
}

namespace Output
{
 class Messager
 {
  public string message = "Default message.";

  public void DisplayMessage()
  {
   System.Console.WriteLine(message);
  }
 }
}

Here's what you see when you run ch03_15.cs:

C:\>ch03_15
Hello from C#.

Namespaces can also extend over multiple files—more on how that works when we discuss assemblies. We took a look at overloading in this chapter—how about overriding? As OOP programmers know, overriding is one of the most important aspects of class inheritance, and it's covered in the next chapter.

  • + Share This
  • 🔖 Save To Your Account