Wednesday, 12 September 2007

C# 3.0 Basic - Collection initializer

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

So
Person p1 = new Person("Jacqualine", "Chow");
Person p2 = new Person("Andre", "Meurer");
Person p3 = new Person("Alex", "James");

List<Person> pList = new List<Person>();
pList.Add(p1);
pList.Add(p2);
pList.Add(p3);

can be written as

List<Person> pList = new List<Person>{ p1, p2, p3};

and in combining the power of object initializer, this will become

List<Person> pList = new List<Person>
{
new Person { Firstname = "Jacqualine", Lastname = "Chow" },
new Person { Firstname = "Andre", Lastname = "Meurer" },
new Person { Firstname = "Alex", Lastname = "James" }
};

No comments:

Post a Comment