Saturday, January 12, 2013

Nested Namespaces in .NET


When organizing your types, you are free to define namespaces within other namespaces. The .NET base class libraries do so in numerous places to provide an even deeper level of type organization. For example, the Collections namespace is nested within System, to yield System.Collections. If you wish to create a root namespace that contains the existing My3DShapes namespace, you can update your code as follows:

// Nesting a namespace.
namespace Chapter3
{
namespace My3DShapes
{
// 3D Circle class.
class Circle{ }
// 3D Hexagon class
class Hexagon{ }
// 3D Square class
class Square{ }
}
}

In many cases, the role of a root namespace is simply to provide a further level of scope, and therefore may not define any types directly within its scope. If this is the case, a nested namespace can be defined using the following compact form:

// Nesting a namespace (take two).

namespace Chapter3.My3DShapes
{
// 3D Circle class.
class Circle{ }
// 3D Hexagon class
class Hexagon{ }
// 3D Square class
class Square{ }
}

Given that you have now nested the My3DShapes namespace within the Chapter3 root namespace,you need to update any existing using directives and type aliases:

using Chapter3.My3DShapes;
using The3DHexagon = Chapter3.My3DShapes.Hexagon;

No comments:
Write comments
Recommended Posts × +