Thursday, December 06, 2007

Auto-Implemented Properties: C# 3.0

Another nice feature of C# 3.0 is Auto-Implemented Properties.

Take the following class implementation:

public class Person
{
private string name;
private bool married;
private int age;

public string Name
{
get
{
return name;
}
set
{
name = value;
}
}

public bool Married
{
get
{
return married;
}
set
{
married = value;
}
}

public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
}
The above code is nothing different to what you do every day. C# 3.0 allows you to cut corners and saves you the need to define a field and its getters and setters for each accessor property. The simple object above can now be written as:

public class Person
{
public string Name
{
get;
set;
}

public bool Married
{
get;
set;
}

public int Age
{
get;
set;
}
}
As with all the new C# 3.0 features, they are designed to make your code cleaner and easier to read. Which is great for us lazy programmers!

Of course if you wanted to implement some kind of event notification or anything other than setting a simple property, you would have to go back to pre C# 3.0 and implement the accessor yourself, oh dear ;)

No comments: