C# 3.0 Automatic properties are a shortcut method for declaring properties on a class. In the code below the Name and Age properties utilise the new C# 3.0 automatic properties, whilst the Address property below illustrates how properties had to be implemented in C# 2.0.
public class Person
{
public string Name { get; set; }
public int Age { get; protected set; }
public string DOB;
private string _address;
public string Address { get { return _address; } set { _address = value; } }
}
With automatic properties you must declare both a get and set accessor, you can make either of the accessors read only by using the private or protected access modifiers.
If you're wondering why you would use this feature instead of simply declaring a public field:
- Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
- You can't databind against a variable. So the DOB field above cannot be databound. Nikhil Kothari's weblog has a good post discussing why Microsoft has not provided functionality to bind to public fields.
- Changing a variable to a property is a breaking change. When compiled to CLI get and set on properties are actually method calls, whereas assignments to and from public fields are not. Changing a field to a property requires all referencing assemblies to be recompiled. You can read about this in further detail in a post by Abhinaba Basu.
If you're wondering why you might still opt to create old school properties and not use this new feature - Breakpoints. You cannot set a breakpoint in the get or set of an automatic property. When debugging an application, it can be extremely useful to be able to set break points to determine when a property is being accessed.