Why is it possible to initialize a Dictionary
like this:
var dict = new Dictionary() {
{ \"key1\", 1 },
{ \"
It does work with the Dictionary, because it has an overload for Add
that takes two arguments. Arrays dont even have an Add
method, let alone one with two arguments.
The Dictionary
class is specially designed to work with KeyValuePair<,>
internally, that is the only reason you do not need the call the constructor manually, instead the two-argument Add
is called and constructs the KeyValuePair under the hood.
Every other IEnumerable
does not have this special implementation and therefore has to be initialized this way:
var array = new KeyValuePair[] {
new KeyValuePair(1, 2),
new KeyValuePair(3, 4)
};
You can create the same behaviour with your own classes, like lets say you implement this:
class ThreeTupleList : List>
{
public void Add(T1 a, T2 b, T3 c)
{
this.Add(new Tuple(a, b, c));
}
// You can even implement a two-argument Add and mix initializers
public void Add(T1 a, T2 b)
{
this.Add(new Tuple(a, b, default(T3)));
}
}
you can initialize it like this, and even mix three-, two- and one-argument initializers:
var mylist = new ThreeTupleList()
{
{ 1, "foo", 2.3 },
{ 4, "bar", 5.6 },
{ 7, "no double here" },
null
};