Tuesday, January 6, 2009

Collection Initializers

Collection initializers are very welcome in C# 3.0. Typing

new List<int> { 1, 2, 3 }

is of course much more convenient then typing

List<int> l = new List<int>();
l.Add(1);
l.Add(2);
l.Add(3);


However, when seeing examples (e.g. MSDN), one could think that you are limited in a single type in a collection initializer. But that is not true. You can use several Add overloads arbitrarily. Having the class

class MyCollection : IEnumerable
{
public void Add(string s) { ... }
public void Add(int i) { ... }
public void Add(SomeClass c) { ... }

//...
}

you can initialize it like this

new MyCollection
{
"something",
1,
2,
new SomeClass { ... },
"yet another string",
3
}