Properties are a natural extension
of fields. Both are named members with associated types, and the syntax for
accessing fields and properties is the same. However, unlike fields, properties
do not denote storage locations. Instead, properties have accessors
that specify the statements to be executed when their values are read or
written.
A property is declared like a field, except that the declaration
ends with a get
accessor and/or a set
accessor written between the delimiters { and } instead of ending in a semicolon. A
property that has both a get
accessor and a set
accessor is a read-write property, a property that has
only a get
accessor is a read-only property, and a property that
has only a set
accessor is a write-only property.
A get
accessor corresponds to a parameterless method with a return value of the
property type. Except as the target of an assignment, when a property is
referenced in an expression, the get accessor of the property is invoked
to compute the value of the property.
A set
accessor corresponds to a method with a single parameter named value and no
return type. When a property is referenced as the target of an assignment or as
the operand of ++
or --,
the set
accessor is invoked with an argument that provides the new value.
The List<T>
class declares two properties, Count and Capacity, which are read-only and
read-write, respectively. The following is an example of use of these
properties.
List<string> names = new List<string>();
names.Capacity = 100; // Invokes set accessor
int i = names.Count; // Invokes get accessor
int j = names.Capacity; // Invokes get accessor
names.Capacity = 100; // Invokes set accessor
int i = names.Count; // Invokes get accessor
int j = names.Capacity; // Invokes get accessor
Similar to fields and methods, C# supports both instance
properties and static properties. Static properties are declared with the static
modifier, and instance properties are declared without it.
The accessor(s) of a property can be virtual. When a
property declaration includes a virtual, abstract, or override modifier, it applies to the
accessor(s) of the property.
Comments
Post a Comment