This is a collection initializer, a C# 3.0 language feature. It requires:
- the type must implement
IEnumerable
(although this is never used for initialization)
- the type must have at least one
Add
method
It simply calls the Add
method for each term.
You can also use tuples if the Add
accepts multiple values, for example dictionaries. Each term is then {key,value}
:
new Dictionary<int,string> {{1,"abc"},{2,"def"}};
For an example of using this for a bespoke type:
class Program
{
static void Main()
{
new Foo { 1, "abc", { 2, "def" } };
}
}
class Foo : IEnumerable
{
public void Add(int a) { }
public void Add(string b) { }
public void Add(int a, string b) { }
// must implement this!! (but never called)
IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}