One of the things I miss about C++ is the #define keyword that allows you to create an abbreviated alias for a long type name. Fortunately, C# provides a way to alias a long namespace or class name while retaining full type-checking.

To alias a namespace or class name, use the using directive to define the alias as shown in the sample code below. Then you can use the alias anywhere you would normally use the class name or namespace. The scope of a using directive is limited to the file in which it appears.

This can be especially handy if you define a class that shares a name with a system-defined class. For example, assume you define your own Button class, and you want to use the WinForms Button class in the same code file. Instead of having to fully qualify the System.Windows.Forms.Button class name every time you use it, you can define an alias with the using directive:

// to alias a namespace
using WinForms = System.Windows.Forms;
// to alias a class name
using WFButton = System.Windows.Forms.Button;

Then when you reference the WinForms button class in your code, you can use the namespace or class name alias you defined:

// use the namespace alias
WinForms.Button button1 = new WinForms.Button();
// or use the class name alias
WFButton button2 = new WFButton();

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot