Demystifying C# 3.0 - Part 5: Object and Collection Initializers

Posted on 6/30/2006 @ 8:46 PM in #Vanilla .NET by | Feedback | 7169 views

As you may already be aware, I am writing up a series of posts on C# 3.0/LINQ and DLINQ, that intend to bring these technologies down to a simple, easy to digest, understandable form. These will be served in small bite sized peices - 5 minutes of your time everyday, and little strokes will fell great oaks. (I am still talking about C# 3.0)

So in this series, we have already talked about -

a) Demystifying C# 3.0 - Part 1: Implicitly Typed Local Variables "var"
b) Demystifying C# 3.0 - Part 2: Anonymous Types
c) Demystifying C# 3.0 - Part 3: Extension Methods
d) Demystifying C# 3.0 - Part 4: Lambda Expressions

Today, lets talk about "Object and Collection Initializers"

First Object Initializers

Lets say, you had a class as shown below -

public class Monkey
{
    private string monkeyName;
    private int age;

 
    public string Name { get { return monkeyName; } set { monkeyName = value; } }
    public int Age { get { return age; } set { age = value; } }

}

The above can be easily instantiated as shown below -

var gwBush = new Monkey{ Name = "George W Bush", Age = 16} ;

The above code simply calls the "setters" of "Monkey" to give you a variable called gwBush back. Note that there is no constructor that accepts the public properties as arguments.

Next, Collection Initializers

Collection initializers, are the corollary of how you'd initialize arrays. Put simply, you can initialize a collection as shown below -

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

So what is the practical upshot of this?

Look at this one line of code -

var theWhiteHouseStaff =
    new List<Monkey>
    {
        new Monkey{ Name = "George W Bush", Age = 16},
        new Monkey{ Name = "Donald Rumsfield", Age = 16},
        new Monkey{ Name = "Condolezza Rice", Age = 16},
        new Monkey{ Name = "Dick Cheney", Age = 16}
    } ;

Boy that sure looks a lot cleaner than a number of temporary variables, hanging chads and recount in florida etc. .. in other words, a much cleaner and terse syntax.

 

Sound off but keep it civil:

Older comments..


On 3/17/2008 7:24:17 AM Anton said ..
We could get even more terse with :

public class Monkey


{


public string Name { get; set; }


public int Age { get; set; }


}