TechEd 2007. More C# 3 features. Object and collection initializers

Another great feature of C# version 3, shown in the TechEd today and yesterday is Object Initializers.

Working as expressions, we can create and initialize objects in a single statement. Imagine we have a class Provider, with properties Name and email. We can do the following:

Provider prv = new Provider() { Name="Microsoft", email = "microsoft@microsoft.com" }

That will create the object and initialize every property we include between the brackets.

In a very similar way work the Collection Initializers, where we can add new items to a collection in the same statement we create it:

List list = new List()
{
new Provider(),
new Provider(),
....
}

And those two features can be nested in the following way:

List list = new List()
{
new Provider() { Name="Microsoft", email = "microsoft@microsoft.com" },
new Provider() { Name="AMD", email = "amd@amd.com" },
....
}

Cheers!