Monday 2 July 2007

Automatic Properties

Automatic Properties is a cool new feature which allows us to define properties with the ease of defining fields.

More often that not, when we expose a property in a class, there is no extra logic within that class, and the property is just a wrapper to a private field. This means we end up with verbose code such as:


public class JobPosting
{
private string _jobTitle;
public string JobTitle
{
get
{
return _jobTitle;
}
set
{
_jobTitle = value;
}
}
}

There is no logic implemented in the property (defined in the example above) and it just acts as a wrapper. Automatic properties allows us to define the same code as above, but in a much prettier fashion.

The following snippet gives an example of the same class as before, but this time in Orcas syntax:

public class JobPosting
{
public string JobTitle { get;set;}
}

As you can see this, is much more readable and compact.

It is important to note that this new orcas style of implementation is NOT equivalent to a field as the compiler will produce the get, set blocks for you. This means that if you do have to implement some logic within your properties, you can use a full get,set block and any external code that uses your class will not require a recompile as the default public interface hasn't changed.

This superb little feature both reduces typing time, improves readability and makes happy little coders.


Roll on Orcas.

No comments: