Labels

Tuesday, April 29, 2008

Object Initializers - Orcas C# New Features

Hi,

This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).

Below are the new features been introduced.

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extension Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Particularly useful when querying and transforming/projecting/shaping data with LINQ.

§ Var Keyword

Object Initializers

When instantiating and using new classes, it is very common to write code like below:

Person person = new Person();
person.FirstName = "Scott";
person.LastName = "Guthrie";
person.Age = 32;

Orcas allows to add take advantage of a great "syntactic sugar" language feature called "object Initializers" that allows you to-do this and re-write the above code as below.

Person person = new Person { FirstName="Scott", LastName="Guthrie", Age=32 };

The compiler will then automatically generate the appropriate property setter code that preserves the same semantic meaning as the previous (more verbose) code sample above.

It works for setting more complex nested property types as well.

Person person = new Person {
FirstName = "Scott",
LastName = "Guthrie"
Age = 32,
Address = new Address {
Street = "One Microsoft Way",
City = "Redmond",
State = "WA",
Zip = 98052
}
};

See great article on its internal working by Bard De Smet. You can read his excellent post on it here.

Reference: http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx

Thanks & Regards,

Arun Manglick || Tech Lead

No comments:

Post a Comment