Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Collection Initializers in C# 3.0

Collection Initializers in C# 3.0

What is a Collection? While merely academic in earlier versions, this seemingly innocent question has important ramifications in C# 3.0.

With C# 3.0, Microsoft intends on supporting several new initialization methods, including one for collections. But in order to leverage that syntax, one has to first define what a collection is. With only 14 BCL classes implementing ICollection, that alone won't cover most scenarios.

Mads Torgersen, Program Manager for the C# language, has offered this definition. A collection is "a type that implements IEnumerable and has a public Add method." In the next version of C#, any type with a public constructor meeting that definition can use the new syntax.

RoleCollection roles = 
    new RoleCollection { "Accounting", "Maintenance", "IT"};

Why did you decide to add a collection initializer?

Mads Torgersen: Array initializers are a convenient and often used feature. It should be just as easy to build and initialize collections, especially now where we are adding LINQ. From a technical standpoint, a projection in LINQ happens within an expression context, so if you want the result of your query to include newly initialized collections, you have to be able to build them without multiple statements.

Do the other teams intend on implementing ICollection on all of the collections in the next version of the BCL?

To increase compatibility for existing code out there we are not allowing changes in existing BCL classes this time around, only additions. So, no. The plans for post-Orcas are not yet clear. It would be nice to see more pickup off the Collection interface in the future, but we'd have to carefully weigh it with compatibility issues - and the time to implement of course :-)

If the class Foo supports ICollection, will you prefer the ICollection.Add method over the Foo.Add method?

That is not currently the plan. There is a case to be made for having the "old" (Collection based) semantics of collection initializers as a backup plan for when that interface is explicitly implemented, but we are currently aiming for the simpler semantics.


Rate this Article