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?
The collection initializer syntax is translated into calls to
Addwith the appropriate number of parameters:This special initializer syntax will also work on other classes that have an
Addmethod and implementsIEnumerable. Let’s create a completely crazy class just to prove that there’s nothing special aboutDictionaryand that this syntax can work for any suitable class:Now you can write this:
Outputs:
See it working online: ideone
As for the other types you asked about:
Addmethod.List<T>has anAddmethod but it has only one parameter.