Why is it possible to initialize a Dictionary<T1,T2>
like this:
var dict = new Dictionary<string,int>() {
{ "key1", 1 },
{ "key2", 2 }
};
...but not to initialize, say, an array of KeyValuePair<T1,T2>
objects in exactly the same way:
var kvps = new KeyValuePair<string,int>[] {
{ "key1", 1 },
{ "key2", 2 }
};
// compiler error: "Array initializers can only be used in a variable
// or field initializer. Try using a new expression instead."
I realize that I could make the second example work by just writing new KeyValuePair<string,int>() { "key1", 1 }
, etc for each item. But I'm wondering if it's possible to use the same type of concise syntax that is possible in the first example.
If it is not possible, then what makes the Dictionary type so special?