Properties are a useful way for a user-defined type to expose data to clients. From the client’s viewpoint, a property appears to be a public field. By implementing a property instead of a field, you can insulate users from the details of your implementation, as well as provide additional processing such as validation or tracing when a property is accessed.
For example, BattingAverage has two public fields: _hits and _atBats. Exposing these fields publicly makes them easily accessible by clients. However, it’s difficult to change the types of these fields, and it’s impossible to perform validation processing when a client updates one of the values.
The _hits and _atBats fields are marked as private in the final version of BattingAverage, shown in the following code, and access to the fields is provided through the Hits and AtBats properties:
public int AtBats { get { return _atBats; } set { TestValid(value, _hits); _atBats = value; } } public int Hits { get { return _hits; } set { TestValid(_atBats, value); _hits = value; } }
A property is defined by specifying its access protection (public in this case), the type for the property value, and the property name. Within the property definition, a get method is used to return the property value, and a set method is used to provide a new value for the property. The set method has a hidden parameter named value that contains the new property value. A read-only property is defined by eliminating the set method.