Information Technology Reference
In-Depth Information
Declaring the Indexer for the Employee Example
Now that you know about indexers, let's declare an indexer for the earlier example: class
Employee .
The indexer must read and write values of type string —so you declare that as the type
of the indexer.
￿
￿
You will arbitrarily index the three fields as integers 0 through 2, so the formal parameter
between the square brackets will be of type int , and you will name it index .
The indexer is declared public so that you can access it easily.
￿
￿
In the body of the set accessor, you determine which field the index refers to, assign
value to it, and return.
In the body of the get accessor, you determine which field the index refers to and return
the value of that field.
￿
class Employee
{
public string LastName; // Call this field 0.
public string FirstName; // Call this field 1.
public string CityOfBirth; // Call this field 2.
public string this[int index] // Indexer declaration
{
set // Set accessor declaration
{
switch (index)
{
case 0: LastName = value;
break;
case 1: FirstName = value;
break;
case 2: CityOfBirth = value;
break;
}
}
get // Get accessor declaration
{
switch (index)
{
case 0: return LastName;
case 1: return FirstName;
case 2: return CityOfBirth;
default:
return "";
}
}
}
}
Search WWH ::




Custom Search