Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Dave Bush has been programming for 20 years. He currently blogs about .NET at http://blog.dmbcllc.com and provides .NET coaching to small and medium sized companies. Dave is a DZone MVB and is not an employee of DZone and has posted 33 posts at DZone. You can read more from them at their website. View Full User Profile

using - There’s More There Than You Are Using

02.02.2009
Email
Views: 1675
  • submit to reddit

If you’ve spent more than a day programming in CSharp, you have already discovered the need for the using directive:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

But, are you aware of the other ways you can use this directive?

For example.  If you have two classes with the same name but under two different namespaces and you need to refer to both of them in the same file, how would you do that?

You could do something like this:

using Namespace.one;
namespace AutoTwit.Code
{
class Sample
{
public void foo()
{
ClassInOneAndTwo v =
new ClassInOneAndTwo();
Namespace.two.ClassInOneAndTwo v2 =
new Namespace.two.ClassInOneAndTwo();
// more code here...
}
}
}

But if you have to do this too much, this becomes awkward at best.

The solution to this problem is to alias namespace two so that you can refer to it with a shorter name:

using Namespace.one;
using T = Namespace.two;
namespace AutoTwit.Code
{
class Sample
{
public void foo()
{
ClassInOneAndTwo v =
new ClassInOneAndTwo();
T.ClassInOneAndTwo v2 =
new T.ClassInOneAndTwo();
// more code here...
}
}
}

Or if you want to make it even shorter, you can alias the class:

using Namespace.one;
using T = Namespace.two.ClassInOneAndTwo;
namespace AutoTwit.Code
{
class Sample
{
public void foo()
{
ClassInOneAndTwo v =
new ClassInOneAndTwo();
T v2 =
new T();
// more code here...
}
}
}

Just think of all the career secure code you could write with this!

Seriously, though.  It has it’s place.  But I could see someone being cute and renaming all the classes they use to one and two character names just so they "don’t have to type so much."

 

References
Published at DZone with permission of Dave Bush, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)