Information Technology Reference
In-Depth Information
Property Declarations and Accessors
Property accessors have predefined names and semantics. They are the
set
accessor and the
get
accessor. You can think of the
set
accessor as a method with a single parameter that “sets”
the value of the property. The
get
accessor has no parameters and returns a value from the
property.
The
set
accessor always has the following:
-
A single, implicit value parameter named
value
, of the same type as the property
A return type of
void
-
The
get
accessor always has the following:
-
No parameters
-
A return type of the same type as the property
The structure of a property declaration is shown in Figure 6-8. Notice in the figure that nei-
ther accessor declaration has
explicit
parameter or return type declarations. They don't need
them, because they are
implicit
in the type of the property.
Figure 6-8.
The syntax and structure of a property declaration
The implicit parameter
value
, in the
set
accessor, is a normal value parameter. Like other
value parameters, you can use it to send data into a method body—or in this case, the accessor
block. Once inside the block, you can use
value
like a normal variable, including assigning val-
ues to it.
Other important points about accessors are the following:
All paths through the implementation of a
get
accessor
must
include a
return
statement
that returns a value of the property type.
The
set
and
get
accessors can be declared in either order, and no methods other than
the accessors are allowed on a property.