
.NET 3.0+C# Automatically Implemented Properties (2)
Often a class may contain properties that provide no behaviour other that permitting the storage of values. This can lead to many space-consuming lines of code for get and set accessors. Using .NET 3.0, these can be replaced with automatic properties.
Read-Only and Write-Only Automatic Properties
When using the shortcut syntax of automatic properties, both a get and set accessor must be provided. Without both accessors, the property would be useless. However, it is possible to create properties that are either read-only or write-only via the public interface whilst allowing the members of the class to use the other accessor internally. This is achieved by declaring one of the accessors as private, or protected if you require access in subclasses.
The following sample shows a read-only and a write-only property:
public int ReadOnly { get; private set; }
public int WriteOnly { private get; set; }
Drawbacks
There are some drawbacks to the use of automatic properties. These must be considered before deciding which syntax to use. Firstly, there is no explicit declaration of a backing store variable. This is created automatically by the compiler but is not available for use by the class' members. Any access to the property value from within its class must be via the property name itself, with the option to use the "this" prefix.
Automatic properties can only be used in situations where simple storage of a value is required. No additional functionality can be added to either of the accessors. This has an additional drawback of not permitting validation to be carried out upon new property values in the set accessor.
With standard property syntax a default value can be applied by simply assigning it to the backing store field in its declaration. Default values cannot be set for automatic properties. To create an apparent default value the property must be initialised in a constructor.
17 May 2008