Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

using - There’s More There Than You Are Using

DZone's Guide to

using - There’s More There Than You Are Using

·
Free Resource

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."

 

Topics:

Published at DZone with permission of Dave Bush, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}