Avoiding Type Name-Clashes using 'using'

Avoiding Type Name-Clashes using 'using'

  • Comments 10

You are already aware that the C# using keyword allows you to supply hints to the compiler regarding the fully qualified name of the types within a given *.cs file. However, what you may not know is that the using keyword also allows you to build aliases (very helpful for prevent name clashes). Assume you have the following two namespace definitions:

namespace My2DShapes
{
  public class Hexagon{} 
}

namespace My3DShapes
{
  public class Hexagon{} 
}

Now assume you wish to create an instance of the 3D Hexagon from the following application:

using My2DShapes;
using My3DShapes;

public class MyApp
{
  public static void Main()
  {
    // Error!  Which Hexagon?
    Hexagon h = new Hexagon();    
  }
}

This name clash can be resolved quite simply by building the following alias:

using My2DShapes;
using The3DHex = My3DShapes.Hexagon;

public class MyApp
{
  public static void Main()
  {
    // This really creates a new My3DShapes.Hexagon.
    The3DHex h = new The3DHex();    
  }
}


Tip from Andrew Troelsen
Posted by: Duncan Mackenzie, MSDN
This post applies to Visual C# .NET 2002/2003/2005

Leave a Comment
  • Please add 5 and 1 and type the answer here:
  • Post
Page 1 of 1 (10 items)