In a project I’m working on, I use complicated Dictionary objects a lot. Often, there are a lot of declarations like:
var d1 = new Dictionary<string, Dictionary<int, List<string>>>();
var d2 = new Dictionary<Tuple<string, string>, List<object>>();
Between typecasts and passing parameters and what not, this gets annoying. What I’d like to do is something like this, using an imaginary keyword “typedel”:
typedel ListDict = Dictionary<string, Dictionary<int, List<string>>>();
typedel PolyDict = Dictionary<Tuple<string, string>, List<object>>();
var d1 = new ListDict();
var d2 = new PolyDict();
So that I do not need to type the long Dictionary declarations every time – so what I want is something like defining shorthand abbreviations for a type name. How can I do this in the simplest way (using the fewest lines of code)?
For a “typedef” that you want to use a lot, you can just create a class that derives from the appropriate base class, as in @Ed S’s answer:
However, this is not the same as what most people consider a typedef: you are introducing a new type, which has implications for things like reflection,
typeof, theisoperator, etc. The distinction may or may not matter to you, but it is there.Within a single source file, however, you can use the second form of the
usingclause to do a real typedef:In either case, while using a “typedef” will definitely save you typing, don’t discount the benefits of seeing the types spelled out explicitly in your code. This is the same reason why articles such as this blog post recommend using
List<Foo>over a customFooCollection : List<Foo>— with the explicit generic version you know what type of collection it is any what methods it exposes.