CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
indexer method. This particular feature is most useful when you are creating custom collection classes
(generic or nongeneric).
Before examining how to implement a custom indexer, let’s begin by seeing one in action. Assume
you have added support for an indexer method to the custom PersonCollection type developed in
Chapter 9 (specifically, the IssuesWithNonGenericCollections project). While you have not yet added the
indexer, observe the following usage within a new Console Application named SimpleIndexer:
// Indexers allow you to access items in an array-like fashion.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Indexers *****\n");
PersonCollection myPeople = new PersonCollection();
// Add objects with indexer syntax.
myPeople[0] = new Person("Homer", "Simpson", 40);
myPeople[1] = new Person("Marge", "Simpson", 38);
myPeople[2] = new Person("Lisa", "Simpson", 9);
myPeople[3] = new Person("Bart", "Simpson", 7);
myPeople[4] = new Person("Maggie", "Simpson", 2);
// Now obtain and display each item using indexer.
for (int i = 0; i < myPeople.Count; i++)
{
Console.WriteLine("Person number: {0}", i);
Console.WriteLine("Name: {0} {1}",
myPeople[i].FirstName, myPeople[i].LastName);
Console.WriteLine("Age: {0}", myPeople[i].Age);
Console.WriteLine();
}
}
}
As you can see, indexers allow you to manipulate the internal collection of subobjects just like a
standard array. Now for the big question: how do you configure the PersonCollection class (or any
custom class or structure) to support this functionality? An indexer is represented as a slightly modified
C# property definition. In its simplest form, an indexer is created using the this[] syntax. Here is the
required update for the PersonCollection class:
// Add the indexer to the existing class definition.
public class PersonCollection : IEnumerable
{
private ArrayList arPeople = new ArrayList();
// Custom indexer for this class.
public Person this[int index]
{
get { return (Person)arPeople[index]; }
set { arPeople.Insert(index, value); }
}
...
400