Wednesday, 12 September 2007

C# 3.0 Basic - Object initializer

This is the first thing I remember from Alex's talk.

According to C# 3.0 specification, "an object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas".

So
Person p = new Person();
p.Firstname = "Jacqualine";
p.Lastname = "Chow";

and

public Person(string firstname, string lastname)
{
this.Firstname = firstname;
this.Lastname = lastname;
}

Person p = new Person("Jacqualine", "Chow");


can be written as
Person p = new Person { Firstname = "Jacqualine", Lastname = "Chow" };

In this case we do not have to create a lot of constructors for different combination of initial parameters.

No comments:

Post a Comment