# C# automatic properties

C# 3.0 makes it very convenient to create properties that doesn’t carry any functionalities besides returning value of attribute and assigning value to it. This new feature is called automatic properties.

Suppose we have a class with big load of properties that just return attribute values and assign given values to them. Something like you can see in following code.

public class Product{    private string description;    private int size;    private decimal price;     public string Description    {        get { return description; }        set { description = value; }    }     public int Size    {        get { return size; }        set { size = value; }    }     public decimal Price    {        get { return price; }        set { price = value; }    }     //...}

All three properties given here are following the same pattern: get returns value of attribute, set assigns value to attribute. There is no more functionality in the bodies of these properties. This pattern gave an idea to language authors. Why not to use some shorter syntax for this kind of properties and let compiler to do all the dirty work? So, here is what we can use in C# 3.0.

public class Product{    public string Description { get; set; }    public int Size { get; set; }    public decimal Price { get; set; }        //...}

Automatic properties are compiled as properties, not as public attributes of class. This way we are able to add functionality to properties later and we doesn’t break connections between class and the other classes.

### 2 thoughts on “C# automatic properties”

• George says:

Why not just make the data member public with a capitalized name (ala property syntax)? Then if you wanted to add behavior, you can add formal property syntax and change the data member to be private with a lower case name. Same diff: you don’t break clients that use property syntax.

• PhillDoc says:

Cool article as for me. I’d like to read more concerning that topic.

• […] are many cool and powerful things we can use to be more productive, faster and better. We have automatic properties, extension methods, partial classes, generics and so on. If we don’t know what they are and […]

• […] some new features also to VB.NET. One of those new features is support for automatic properties. C# automatic properties are here from .Net Framework 3.5 and now are them also in VB.NET. In this posting I will show to […]