This is called a collection initializer. It’s calling the parameterless constructor, and then calling Add:
List<int> tmp = new List<int>();
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
List<int> intList = tmp;
The requirements for the type are:
- It implements
IEnumerable - It has overloads of
Addwhich are appropriate for the argument types you supply. You can supply multiple arguments in braces, in which case the compiler looks for anAddmethod with multiple parameters.
For example:
public class DummyCollection : IEnumerable
{
IEnumerator IEnumerable.GetEnumerator()
{
throw new InvalidOperationException("Not a real collection!");
}
public void Add(string x)
{
Console.WriteLine("Called Add(string)");
}
public void Add(int x, int y)
{
Console.WriteLine("Called Add(int, int)");
}
}
You can then use:
DummyCollection foo = new DummyCollection
{
"Hi",
"There",
{ 1, 2 }
};
(Of course, normally you’d want your collection to implement IEnumerable properly…)