O'Reilly logo

Learning C# by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Indexers

Some classes act like collections. For example, a ListBox class might act as a collection of the strings it displays. You might write your own School class that would act as a collection of all the Students enrolled in the school.

An indexer is a C# construct that allows you to treat a class as if it were a collection, using the familiar [] syntax of arrays. This lets you write:

mySchool[5];

to obtain the sixth Student in your School object.

An indexer is actually a special kind of property that includes get() and set() methods to specify its behavior. Declare an indexer property within a class using the following syntax:

            type this [type argument]{get; set;}

The type specifies the type of object that returns the indexer, while the type argument within the square brackets specifies what kind of argument is used to index into the collection that contains the target objects.

Tip

The square brackets do not indicate that type argument is optional. The square brackets themselves are part of the syntax of the indexer.

Although it is common to use integers as index values, you can index a collection on other types as well, including strings. This lets you write:

mySchool["John Galt"];

to index into your School’s internal collection and find the Student object whose name field (for example) matches the index string.

You can even provide an indexer with multiple parameters if you wish to provide the syntax for accessing into your class as if it were a multidimensional array!

The ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required