using – There’s more there than you are using

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, it 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 its 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.”

Related Post

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear