Skip to Main Content
Programming C#
book

Programming C#

by Jesse Liberty
July 2001
Intermediate to advanced content levelIntermediate to advanced
688 pages
16h 14m
English
O'Reilly Media, Inc.
Content preview from Programming C#

Namespaces

Chapter 2 discusses the reasons for introducing namespaces into the C# language (e.g., avoiding name collisions when using libraries from multiple vendors). In addition to using the namespaces provided by the .NET Framework or other vendors, you are free to create your own. You do this by using the namespace keyword, followed by the name you wish to create. Enclose the objects for that namespace within braces, as illustrated in Example 3-19.

Example 3-19. Creating namespaces

namespace Programming_C_Sharp 
{
   using System;
   public class Tester
   {

      public static int Main(  )
      {
         for (int i=0;i<10;i++)
         {
            Console.WriteLine("i: {0}",i);
         }
         return 0;
      }
   }
}

Example 3-19 creates a namespace called Programming_C_Sharp, and also specifies a Tester class which lives within that namespace. You can alternatively choose to nest your namespaces, as needed, by declaring one within another. You might do so to segment your code, creating objects within a nested namespace whose names are protected from the outer namespace, as illustrated in Example 3-20.

Example 3-20. Nesting namespaces

namespace Programming_C_Sharp 
{
   namespace Programming_C_Sharp_Test
   {
      using System;
      public class Tester
      {

           public static int Main(  )
           {
               for (int i=0;i<10;i++)
               {
                  Console.WriteLine("i: {0}",i);
               }
              return 0;
           }
       }
   }
}

The Tester object now declared within the Programming_C_Sharp_Test namespace is:

Programming_C_Sharp.Programming_C_Sharp_Test.Tester

This name would not conflict with another Tester object in any other namespace, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming C#, Second Edition

Programming C#, Second Edition

Jesse Liberty
Programming C# 12

Programming C# 12

Ian Griffiths
Programming C# 8.0

Programming C# 8.0

Ian Griffiths

Publisher Resources

ISBN: 0596001177Supplemental ContentCatalog PageErrata