Playing Chicken With Common Sense

Using Type Alias

I am surprised how many people still don't know they can alias namespaces using the C# keyword using.  Resharper automatically adds this syntax for me and it seems like 1 person a month says that didn't know.

   1: using Short = Company.Project.Task.Function;

The reason for this post; however, is to show another usage of the C# keyword using.  I saw this and thought it was worth your time.  When using generics the < and > can become unreadable at times and with a little help from "using" we can make it look nice.  Let's look at an example:

   1: Dictionary<int, string> idNameMapping;

Or we might have even more complex data structures where Id is mapped to another dictionary:

   1: Dictionary<int, Dictionary<string, int>> complexIdMapping;

Well that doesn't look so great and if we had more generics then it would look even worse.  Now with a little help from "using" we can clean it up.

   1: using Item = System.Collections.Generic.Dictionary<string, string>;
   3: namespace wijix
   4: {
   5:     using Records = Dictionary<int, Item>;
   6:     public class Controller
   7:     {
   8:         Records recordDictionary = new Records();
   9:     }
  10: }

Now...  I may never do this in my code but it was interesting to know.

  • E-mail
  • Kick it!
  • Shout it
  • Bookmark and Share


Brad Merrell Brad Merrell   United States 7/21/2008 3:42:04 PM #

When I learned the "Using" block it changed my perceptive and way of programming.  I think this is another of those concepts that will affect how I programm going forward.  Thanks for presenting it.

Control panel


Comment RSS