CHAPTER 19

image

Namespaces

Namespaces provide a way to group related top-level members into a hierarchy. They are also used to avoid naming conflicts. A top-level member, such as a class, that is not included in a namespace is said to belong to the default namespace. It can be moved to another namespace by being enclosed in a namespace block. The naming convention for namespaces is the same as for classes, with each word initially capitalized.

namespace MyNamespace
{
  class MyClass {}
}

Nested namespaces

Namespaces can be nested any number of levels deep to further define the namespace hierarchy.

namespace MyNamespace
{
  namespace NestedNamespace
  {
    class MyClass {}
  }
}

A quicker way to write this is to just separate the namespaces with a dot.

namespace MyNamespace.NestedNamespace
{
  class MyClass {}
}

Note that declaring the same namespace again in another class within the project has the same effect as if both namespaces were included in the same block, even if the class is located in another code file.

Namespace access

To access a class from another namespace its fully qualified name needs to be specified.

namespace MyNamespace.NestedNamespace
{
  public class MyClass {}
}
  
namespace OtherNamespace
{
  class MyApp
  {
    static void Main()
    {
      MyNamespace.NestedNamespace.MyClass myClass;
    }
  }
}

Using directive

The fully qualified name can be shortened by including the namespace with a using directive. The members of that namespace can then be accessed anywhere in the code file without having to prepend the namespace to every reference. It is mandatory to place using directives before all other members in the code file.

using MyNamespace.NestedNamespace;

Having direct access to these members means that if there is a conflicting member signature in the current namespace the member in the included namespace will be hidden. For example, if there is a MyClass in the OtherNamespace as well, that class will be used by default. To use the class in the included namespace, the fully qualified name would again have to be specified.

using MyNamespace.NestedNamespace;
  
namespace MyNamespace.NestedNamespace
{
  public class MyClass
  {
    public static int x;
  }
}
 
  
namespace OtherNamespace
{
  public class MyClass
  {
    static void Main()
    {
      int x = MyNamespace.NestedNamespace.MyClass.x
    }
  }
}

To simplify this reference, the using directive can instead be changed to assign the namespace to an alias.

using MyAlias = MyNamespace.NestedNamespace;
// ...
int x = MyAlias.MyClass.x;

An even shorter way would be to define the fully qualified class name as a new type for the code file, by using the same alias notation.

using MyType = MyNamespace.NestedNamespace.MyClass;
// ...
int x = MyType.x;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.204.201