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>;Isn't that cool? Instead of typing in a lot of nested types with all that < and > we can get "normal" looking type names.
namespace Sample
{
using Records = Dictionary<int, Item>;
public class Controller
{
Records recordDictionary = new Records();
}
}
What do I read:
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:
ReplyDeleteusing RecordDictionary = Dictionary<int,Item>;
.
.
RecordDictionary records = new RecordDictionary();
Cheers!
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.
ReplyDeleteThanks for the quick tip!
oj,
ReplyDeleteI 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.
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.
ReplyDeleteJosh.
If you're going for brevity, just forsake defining the type at all and use the "var" keyword to define an anonymous type.
ReplyDeletevars are supported only from C# 3.5
ReplyDeleteGreat article, thanks for the tip!
ReplyDeletePECS is Microsoft & ISO 9001 certified company that provide new media
ReplyDeletesolutions 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.