Saturday, January 12, 2013

Custom Namespaces in .NET


Assume you are developing a collection of geometric classes named Square, Circle, and Hexagon.Given their similarities, you would like to group them all together into a common custom namespace.You have two basic approaches. First, you may choose to define each class within a single file (shapeslib.cs) as follows:

// shapeslib.cs

using System;
namespace MyShapes
{
// Circle class.
class Circle{ /* Interesting methods... */ }
// Hexagon class.
class Hexagon{ /* More interesting methods... */ }
// Square class.
class Square{ /* Even more interesting methods... */ }
}

Notice how the MyShapes namespace acts as the conceptual “container” of these types. Alternatively,

you can split a single namespace into multiple C# files. To do so, simply wrap the given class

definitions in the same namespace:

// circle.cs

using System;
namespace MyShapes
{
// Circle class.
class Circle{ }
}

// hexagon.cs

using System;
namespace MyShapes
{
// Hexagon class.
class Hexagon{ }
}

// square.cs

using System;
namespace MyShapes
{
// Square class.
class Square{ }
}

As you already know, when another namespace wishes to use objects within a distinct namespace,the using keyword can be used as follows:

// Make use of types defined the MyShape namespace.

using System;
using MyShapes;
namespace MyApp
{
 class ShapeTester
  {
   static void Main(string[] args)
   {
    Hexagon h = new Hexagon();
    Circle c = new Circle();
    Square s = new Square();
   }
  }
}

No comments:
Write comments
Recommended Posts × +