Labels

Tuesday, April 29, 2008

Automatic Properties - 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

Automatic Properties

Till now, below is the code for properties get/set.

public class Person

{
private string _firstName;
private string _lastName;


public string FirstName

{
get {return _firstName;}
set {_firstName = value;}
}

public string LastName

{
get {return _lastName;}
set {_lastName = value;}
}
}

The new feature ‘Automatic properties’ allow you to avoid having to manually declare a private field and write the get/set logic -- instead the compiler can automate creating the private field and the default get/set operations for you. It allows you to-do this and re-write the above code as below.

When the C# "Orcas" compiler encounters an empty get/set property implementation like above, it will do as below.

· Automatically generate a private field for you within your class, and

· Implement a public getter and setter property implementation to it

Note: Just use the "prop" code snippet in Visual Studio, this is much cleaner in case you don't need the private fields at all.


public class Person

{

public string FirstName { get; set; }

public string LastName { get; set; }

}

Or as below:

public class Person

{

public string FirstName

{

get;

set;

}

public string LastName

{

get;

set;

}

}

Note: Notice that automatic properties should have both a getter and a setter declared. Read-only or write-only properties are not permitted.

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