Collection initializers
A collection initializer specifies the elements of a collection. collection-initializer: element-initializer-list: element-initializer: expression-list: A collection initializer consists of a sequence of element initializers, enclosed by { and } tokens and separated by commas. Each element initializer specifies an element to be added to the collection object being initialized, and consists of a list of expressions enclosed by { and } tokens and separated by commas. A single-expression element initializer can be written without braces, but cannot then be an assignment expression, to avoid ambiguity with member initializers. The non-assignment-expression production is defined in §7.18. The following is an example of an object creation expression that includes a collection initializer: List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. Thus, the collection object must contain an applicable Add method for each element initializer. The following class represents a contact with a name and a list of phone numbers: public class Contact public string Name { get { return name; } set { name = value; } } public List<string> PhoneNumbers { get { return phoneNumbers; } } A List<Contact> can be created and initialized as follows: var contacts = new List<Contact> { which has the same effect as var __clist = new List<Contact>(); where __clist, __c1 and __c2 are temporary variables that are otherwise invisible and inaccessible.
|