Monday, March 31, 2008 9:30 PM
Aliases are a little known feature of .NET that, despite have been around for quite a long time, are actually quite underused. "What is an alias" you may ask? An alias allows you to assign a nickname to a certain class or namespace and then refer to that nickname in code instead. Normally they're used to increase readability, or to help to clarify naming collisions. Take the following code, for example...
static void Main(string[] args)
{
FancyControlVendor.Organizer.BusinessObjects.Email organizerEmail = _mailBox.GetSelectedEmail();
Microsoft.Outlook.Interop.Email outlookEmail = new Microsoft.Outlook.Interop.Email();
outlookEmail.Subject = organizerEmail.Subject;
outlookEmail.Body = organizerEmail.Body;
_emailRepository.Save(outlookEmail);
}
Not exactly clean, is it? In this example, we're writing a plug-in to create emails for Outlook from a third party UI vendor's proprietary mailbox control. Unfortunately, both Outlook and the vendor chose to name their primary business object "Email", which forces us to fully qualify the exact type of Email we're trying to use each time we reference it. Imagine if we could temporarily rename each of these Email objects to something more descriptive. With aliases, we can...
using FancyControlsEmail = FancyControlVendor.Organizer.BusinessObjects.Email;
using OutlookEmail = Microsoft.Outlook.Interop.Email;
namespace AliasExample
{
class Program
{
static void Main(string[] args)
{
FancyControlsEmail organizerEmail = _mailBox.GetSelectedEmail();
OutlookEmail outlookEmail = new OutlookEmail();
outlookEmail.Subject = organizerEmail.Subject;
outlookEmail.Body = organizerEmail.Body;
_emailRepository.Save(outlookEmail);
}
}
}
In this version, we've added appropriate aliases to each of the types so that not only can we tell at a glance the exact kind of object that we're working with, but we've also reduced our overall code bloat. The first two using statements in at the top of the file are our actual aliases. Notice that these are almost identical to a standard using statement with the exception of the equals sign between the nickname and the fully qualified class name. Now, whenever we use these objects in code we can simply refer to them by their aliased name instead of their fully qualified name. We can also use this same technique for long namespaces.
This is a great way to keep your code clean and maintainable.