
.NET 3.0+C# Automatically Implemented Properties
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.
A Simple Property
Class properties are used to provide the publicly visible aspects of state of an object. Often a property performs some calculation or lookup before returning this state. However, in many cases the property simply holds a value that can be manipulated or read by other classes.
To create such a property using the normal, longhand method, three elements are required. The first is the property declaration, which determines the type and the name of the property. The second items required are the accessors. These allow the data in the property to be read or written to, and determine whether the property is fully accessible, read-only or write-only. Finally, a backing store field is required. This is the variable that holds the property's value and is usually declared as either private or protected.
The following code declares a class with a single property that contains all of the above elements:
class Employee
{
private string _name; // Backing Store
public string Name // Property Declaration
{
get // Get Accessor
{
return _name;
}
set // Set Accessor
{
_name = value;
}
}
}
This syntax for declaring a read/write property includes a large number of lines of code for a relatively simple task. Using the layout and formatting shown, a single property involves twelve lines. For a class containing just ten properties, one hundred and twenty lines would be required, limiting the ability to easily read and comprehend the class' public interface.
Automatically Implemented Properties
Automatic properties were introduced in C# in the .NET framework version 3.0. The external behaviour of automatic properties is identical to that of the simple properties explained above. They provide state that can be manipulated and read externally and permit the declaration of fully accessible, read-only or write-only properties.
The difference between standard properties and automatically implemented properties is in the syntax used for their declaration. Auto properties can be declared in a single statement. This allows more compact and easy-to-understand programs.
To create a simple, fully accessible property using this alternative syntax, the declaration remains the same but the accessors are created without a code block. The following class is the shorthand version of that seen previously.
class Employee
{
public string Name {get; set;}
}
17 May 2008