Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do array semantic initializers work in C#?

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.

like image 473
Erik Funkenbusch Avatar asked Dec 23 '22 09:12

Erik Funkenbusch


1 Answers

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 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.

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.

like image 180
mmx Avatar answered Jan 05 '23 00:01

mmx