Why is it possible to initialize a Dictionary
like this:
var dict = new Dictionary() {
{ \"key1\", 1 },
{ \"
The collection initializer syntax is translated into calls to Add
with the appropriate number of parameters:
var dict = new Dictionary();
dict.Add("key1", 1);
dict.Add("key2", 2);
This special initializer syntax will also work on other classes that have an Add
method and implements IEnumerable
. Let's create a completely crazy class just to prove that there's nothing special about Dictionary
and that this syntax can work for any suitable class:
// Don't do this in production code!
class CrazyAdd : IEnumerable
{
public void Add(int x, int y, int z)
{
Console.WriteLine(x + y + z); // Well it *does* add...
}
public IEnumerator GetEnumerator() { throw new NotImplementedException(); }
}
Now you can write this:
var crazyAdd = new CrazyAdd
{
{1, 2, 3},
{4, 5, 6}
};
Outputs:
6
15
See it working online: ideone
As for the other types you asked about:
Add
method.List
has an Add
method but it has only one parameter.