3.7 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, including the outer namespace Programming_C_Sharp.



Programming C#
C# Programming: From Problem Analysis to Program Design
ISBN: 1423901460
EAN: 2147483647
Year: 2003
Pages: 182
Authors: Barbara Doyle

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