This is the only function - collection initializers . Like object initializers, it can only be used as part of an object initialization expression, but basically it calls Add
with any arguments — using curly brackets to specify multiple arguments or single arguments at a time without additional curly braces, for example
var list = new List<int> { 1, 2, 3 };
See Section 7.6.10.3 of the C # 4 Specification for more information.
Note that for collection initializers, you need to use two things like:
- It should implement
IEnumerable
, although the compiler does not call GetEnumerator
calls - It must have appropriate overloads for the
Add
method.
For instance:
using System; using System.Collections; public class Test : IEnumerable { static void Main() { var t = new Test { "hello", { 5, 10 }, { "whoops", 10, 20 } }; } public void Add(string x) { Console.WriteLine("Add({0})", x); } public void Add(int x, int y) { Console.WriteLine("Add({0}, {1})", x, y); } public void Add(string a, int x, int y) { Console.WriteLine("Add({0}, {1}, {2})", a, x, y); } IEnumerator IEnumerable.GetEnumerator() { throw new NotSupportedException(); } }
source share