Collection initializers: adding multiple values

Collection initializer are a wonderful feature in C# 3.0. Instead of calling the Add method of the collection for each item that should be added to the collection it’s possible to add the items in curly brackets after the constructor call; the approach looks very similar to how to initialize arrays with a fixed set of values:

// create a list and add items to it.
var list = new List<int>() { 1, 2, 3, 5, 6, 2, 3, 9, 6, 4 };

This code is unfolded by the C# compiler to something like this (not exactly like this but very similar):

// create a list.
var list = new List<int>();
// add the items to it.
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(5);
// …
 

This pattern works wonderful with a list that exposes an Add method that expects only one argument. But does this model also work with, for example a Dictionary<K, V>? The dictionary class has an Add method that expects two values: a key and a value.

The answer is yes; the scenario extends also to a dictionary. The code to initialize a dictionary with values looks very like the mathematical notation for a set holding sub sets:

// create a dictionary and initialize it with values.
var dictionary = new Dictionary<string, int>()
{
    { “Hello”, 1 },
    { “World”, 2 }
}

After having found out that this works I went curious and tried the notation (the embedded curly brackets) also with the list class:

var list = new List<int> { { 1 }, { 2 } };

The C# compiler doesn’t create any warning or error for this piece of code. It seems as if you can always put the items that are added to a list also into the curly brackets.

Now, this made even more curious and created a class that has an Add method that expects three arguments:

class FooList
{
    public void Add(int index, string key, string value)
    {
        // code to add the item to the list
    }
}

To add items to the FooList I added the following code to the application:

// create the foo list and add values to it.
var foo = new FooList()
{
    { 1, “key1″, “value1″ },
    { 2, “key2″, “value2″ }
};

… and the unexpected happened: this piece of code didn’t compile. But it wasn’t the initialization that gave me a compiler error but it was the implementation of the FooList.

The C# compiler wanted me to implement the IEnumerable interface into the FooList; otherwise the collection initializer isn’t allowed. This makes sense because all lists (or collections for that matter) need to implement the interface and collection initalizer should only be available for data structures that are implemented to hold a set of items.

After adding the IEnumerable implementation the code looked something like this:

class Foo : IEnumerable<KeyValuePair<string, string>>
{
    public void Add(int index, string key, string value)
    {
        // code to add the item to the list
    }

    #region IEnumerable<KeyValuePair<string, string>> Members

    public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
    {
        // code to implement the enumerator.
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator
        System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

    #endregion
}

I like the collection initialization pattern very much. But more than that it is really cool that the C# team made them very flexible. This allows the developers to use it in a varity of scenarios and doesn’t limit it to the initialization of lists with just one value! Great job, great feature!

Published on Apr 29th, 2008 — Tags: , ,
Comments (0)    digg it!    kick it   

Delegates vs Lambda Expressions

What the difference between

static bool FinderMethod(int value)
{
    // check whether the current value should be returned.
    return (value > 5);
}

// … other code

// return all values higher than 5.
List<int> result = list.FindAll(new Predicate<int>(FinderMethod));

and the following lambda expression

// return all values higher than 5.
List<int> result = list.FindAll(value => value > 5);

for the .NET CLR (common language runtime)?

Answer
None! The C# compiler converts the second snippet into the same code that is found in the first one. That’s done because the CLR doesn’t know anything about lambda expressions. They are only a language construct and therefore converted to a delegate call and a method by the compiler.

The following is a Reflector screenshot that shows the lambda expression how it is translated by the C# compiler:

Published on Apr 20th, 2008 — Tags: , , ,
Comments (1)    digg it!    kick it   

Chris at the profs: Compilers, Languages and the Future

A few days ago - while being on the road for our Academic Community Launch - Mario, Alex and I had the chance to speak with Hanspeter M?ssenb?ck, professor at the University of Linz, and Markus L?berbauer, who is an assistant at the university.

During the interview we have spoken about languages, compilers, the work at university and what is going to come up in the future. Prof. M?ssenb?ck and Mr. L?berbauer also gave us information on what students should study to be ready for the future.

Tune in if you are interested in languages, compilers, the .NET Framework and JAVA.

Published on Apr 16th, 2008 — Tags: , , , ,
Comments (0)    digg it!    kick it   

Pictures taken at the Community Launch

Our Academic Community Launch is a big success (more than 100 people were attending at some locations). I thought I could post some pictures to show all of you how we are doing and what we are doing.

People attending at the Community Launch:

Mario presenting Visual Studio 2008, VSTO, WPF, WCF and Silverlight:

We organized also a buffet for the people who were attending:


Me presenting .NET 3.5, LINQ and C# 3.0:

Alex presenting LINQ to SQL, Entity Framework, the SQL Server 2008 family and ASP.NET MVC:

The whole load of pictures is found here.

Published on Apr 15th, 2008 — Tags: , ,
Comments (2)    digg it!    kick it   

Academic Community Launch: Wo sind die Beispiele von gestern?

The following post is in German and contains information for the people who are attending at our “Academic Community Launch” tour.

Gestern habe ich w?hrend meines Vortrages Beispiele zu C# 3.5 (also die neuen Features der Sprache und des Compilers) gezeigt. Leider k?nnen die Beispiele noch nicht von unserer offiziellen Community Launch Webseite heruntergeladen werden. Deshalb stelle ich den Code von gestern hier online.

Anfang der n?chsten Woche wird werden die Beispiele dann auch auf der offiziellen Academic Community Launch Webseite verf?gbar sein.

Sollte es Feedback oder Fragen zum Vortrag oder zu C# 3.5 geben, k?nnen Sie mich gerne unter christian@liensberger.it erreichen. :-)

Published on Apr 11th, 2008 — Tags:
Comments (3)    digg it!    kick it   

Meet me at the Big>Days (Heroes Happen Here) in Vienna

I’m going to be one of the experts (at the Ask the Experts counter) at the Big>Days in Vienna (same as the Heroes Happen Here event in the other countries). I’ll be there on the 8th of April; the whole day long.

If you want to meet me and speak about ideas or just ask me questions about .NET 3.5 please visit me and my collegues, Christian Nagel and Klaus Aschenbrenner, there.

I’m already really excited about being one of the experts there. It’s the first time that I’m an expert at a Microsoft event; I hope more are to come ;)

See you there!

Published on Apr 2nd, 2008 — Tags: , ,
Comments (0)    digg it!    kick it