2

Basically my question is about the following:

using myName = System.Web;

I recently came across some code which did something very similar to that above.
My question boils down to the following points:

  1. What is doing this even called?
  2. Why would you need to this?
  3. Pros/Cons of doing this?

I understand one of the benefits in which I have used this type of declaration:

using Security = System.Web.Security;

...

_roles = (SimpleRoleProvider)Security.Roles.Provider;
_membership = (SimpleMembershipProvider)Security.Membership.Provider;

As I had an entity named Membership I couldn't just do Membership.Provider without a conflict. So here the using declaration allows me to shortern the full use of System.Web.Security.Membership to just Security.Membership.Provider which feels nicer from an OCD point of view.

Ashley Medway
  • 7,151
  • 7
  • 49
  • 71
  • Agreed thats its a duplicate now that I know what its called, I feel it should stay active as a linking question. For others like me who might be lost :) – Ashley Medway Jan 03 '14 at 09:15

3 Answers3

5

This is a using directive also called an namespace alias.

If you have two types of the same name but from different namespaces, you need to spell out the namespace every time you use that type. If it's a long namespace, you may want to give it an alias.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
2

It is called a namespace alias or using directive.

The using Directive (C# Reference) can also be used to create an alias for a namespace. For example, if you are using a previously written namespace that contains nested namespaces, you might want to declare an alias to provide a shorthand way of referencing one in particular

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
2

1) Its called namespace aliasing.

2) People do it for one reason mainly: resolving ambiguous references.

3) I hate it.. so I'll give you a con: an alias can be anything.. so it can make the code hard to read. Standards are rarely followed when applied, so one file might have an alias Entities and another file EntitiesCore .. for the same namespace. Hard to follow.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138