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
0 Comments:
Post a Comment
<< Home