Information Technology Reference
In-Depth Information
The get Accessor
When the indexer is used to retrieve a value, the
get
accessor is called with one or more index
parameters. The index parameters represent which value to retrieve.
string s = emp[0];
↑
Index parameter
Your code in the
get
accessor body must examine the index parameters, determine which
field they represent, and return the value of that field.
The syntax and meaning of the
get
accessor are shown in Figure 6-18. The left side of the
figure shows the actual syntax of the accessor declaration. The right side shows the semantics
of the accessor if it were written using the syntax of a normal method. The semantics of the
get
accessor are as follows:
It has the same parameter list as in the indexer declaration.
It returns a value of the same type as the indexer.
Figure 6-18.
The syntax and meaning of the get accessor declaration
More About Indexers
As with properties, the
get
and
set
accessors cannot be called explicitly. Instead, the
get
acces-
sor is called automatically when the indexer is used in an expression for a value. The
set
accessor is called automatically when the indexer is assigned a value with the assignment
statement.
When an indexer is “called,” the parameters are supplied between the square brackets.
Index
Value
↓
↓
emp1[0] = "Doe"; // Calls set accessor
string NewName = emp[0]; // Calls get accessor
↑
Index