Friday, July 18, 2008

"Using" magic or working with type aliases



Generics in C# allow us specify and construct rather complex types. For instance, we can create a dictionary that maps Id number with the name:

Dictionary<int, string> idNameMapping;
We can create even more complex data structure, when Id number has to be mapped on another dictionary:
Dictionary<int, Dictionary<string, int>> complexIdMapping;
Nothing can stop us if we want put another types into dictionary (or any generic type) declaration.

You've noticed already that the more types we put into declaration the more clumsier it becomes. I'm not even mentioning typing effort :).
Here's how "using" keyword can help us reduce typing and introduce some level of self-documentation for the code.
using Item = System.Collections.Generic.Dictionary<string, string>;
namespace Sample
{
using Records = Dictionary<int, Item>;
public class Controller
{
Records recordDictionary = new Records();
}
}
Isn't that cool? Instead of typing in a lot of nested types with all that < and > we can get "normal" looking type names.

What do I read:

8 comments:

  1. I don't mean to sound awful, but aliasing has been around since C# was first released and hence this is really old news. Using it with generics doesn't make it any more exciting than it always has been. BTW, calling your dictionary type "Records" is counterintuitive. Your code would read much better like this:

    using RecordDictionary = Dictionary<int,Item>;
    .
    .
    RecordDictionary records = new RecordDictionary();

    Cheers!

    ReplyDelete
  2. Atually, while using is old news, I (and I'm sure others as well) never knew it was possible to use them with the generic type parameters. That's news to me, and I'm sure I'll get to use it sometime.

    Thanks for the quick tip!

    ReplyDelete
  3. oj,
    I wasn't going to announce new features. The aim of the post was to use aliasing with generics to provide more brevity to the code(reduce typing).

    RecordsDictionary is pretty self documenting name :), thanks.

    ReplyDelete
  4. Wow, I've been aliasing with the Using statement for the last couple of years and even so didn't know that you could alias a complete type definition. I stopped short at simple namespace brevity. Thanks for posting this.

    Josh.

    ReplyDelete
  5. If you're going for brevity, just forsake defining the type at all and use the "var" keyword to define an anonymous type.

    ReplyDelete
  6. vars are supported only from C# 3.5

    ReplyDelete
  7. Great article, thanks for the tip!

    ReplyDelete
  8. PECS is Microsoft & ISO 9001 certified company that provide new media
    solutions all across the globe having sales office in UK and India. We
    provide solutions related Web Design & Development, SEO and Bespoke
    Software for all business domains.

    ReplyDelete