in C# 3, initializers were added. This is a great feature. However, one thing has me confused.
When you initialize class, you typically have to specify the member variable or property you are initializing. For example:
class C { public int i; }
public void blah() {
C c = new C() { i = 1 };
}
Array semantics have been in C# since the beginning, i think. But they don't behave like that. For example
public void foo()
{
int[] i = new int[] { 0, 1, 2, 3 };
}
All fine and good, but what about classes with array semantics?
public void bar()
{
List<int> li = new List<int>() { 0, 1, 3, 3 };
}
List is just a class, like any other (though it is a generic).
I'm trying to figure out how the compiler initializes the List member. Is this some kind of magic done behind the scenes? Or is this something related to there being an indexer defined on the class?
Thanks.
C# Language Specification v3.0 Section 7.5.10.3 Collection Initializers:
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 anAdd
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 applicableAdd
method for each element initializer.
To enable this feature for your own collections, you just need to have an Add
method with appropriate parameters. The compiler will transform it to a sequence of calls to the Add
method with the arguments you specified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With