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: