Page 88      All Pages  All Books
Introducing C# Programming • Chapter 2           61
1
Employee employee = employees.getEmployee( i ); Console.WriteLine( employee.LastName ); }
However, it would be more intuitive if we could just treat the list of employees as an array contained with the Employee object. Here is what that might look like:
for ( i = 0; i < employees.Length; i++ ) {
Console.WriteLine( employees.[i].LastName ); }
This is precisely what indexers do. They let you use array syntax to access a list of objects contained inside another class. Indexers do not imply a specific implementation for the list, however. The list within the containing class could be a static array, a file on disk, one of the collection classes supplied by the .NET Framework, or some other implementation. If the underlying implementation is changed from a static array to a collection class, for example, a programmer using the Employees class would not need to change her code. This is highly desirable and analogous to the same situation described in the section discussing properties in this chapter. Figure 2.6 extends the code listing in Figure 2.5 to make use of an indexer to iterate through a list of employees. The program is included on the CD in the file Indexers.cs.
Figure 2.6 The Indexers.cs Program Listing
using System;
using System.Collections;
/// <summary>
/// Contains the program entry point for the Indexers Sample.
/// </summary>
class IndexersSample
{
static void Main( string[] args ) {
try {
Continued

Page 88      All Pages  All Books