Collection initializers
Freya have another new feature borrowed from C# 3.0: collection initializers.
var L := new List[Integer]![1, 2, 3, 4];
As you can see, an array literal can be appended to the creation of any class implementing the generic ICollection[T] interface type. But, this time, the array literal doesn't generates an array at runtime. Instead, for each item in the literal, a call to the method Add, from the collection, is generated.In order to realize why we need collection initializers, you must weight the alternative method:
var L := new List[Integer]([1, 2, 3, 4]);
In this case, the array literal is passed as a parameter to the constructor call. However, the parameter is declared as IEnumerable[T]. Can you see what it means? A temporal array must be generated and initialized, item by item. Then, the array must be casted as a IEnumerable[T] reference, which will be passed to the constructor. Inside the constructor, GetEnumerator is called, and a second temporal object is created. Finally, a loop is performed, in order to add an item for each enumerated item.
Labels: creation, initializer
So, we have a "normal" instance construction followed by property or field assignments. Does this remind you any other existing C# feature? Sure, that's how custom attributes are instantiated. Custom attributes mix positional parameters corresponding to constructor parameters, and named parameters, which must be translated as post-construction assignments. We could extend the syntax from custom attributes to object creation:
