views:

160

answers:

2

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.

+2  A: 

From my somewhat limited understanding, List uses a different semantic known as collection initializer. That may account for the difference.

AngryHacker
You're correct. It's a collection initializer. It's new to C# 3.0 http://msdn.microsoft.com/en-us/library/bb384062.aspx
Dan Herbert
+7  A: 

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.

Mehrdad Afshari
Ahh.. so it is in fact behind the scenes magic. Thanks.
Mystere Man