O'Reilly logo

C# Primer: A Practical Approach by Stanley B. Lippman

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

2.5. Indexers

An indexer provides support for arraylike indexing of a class object. An indexer looks like a property. Like a property, an indexer provides a get and set pair of accessors. Unlike a property, however, an indexer is identified using the this keyword rather than a name. Indexers require at least one index parameter. The index can be of any type.

For example, imagine that users have requested the ability to retrieve the occurrence count of a word using the following subscript syntax:

int count = theObj[ "fiery" ];

How can we support that? The following indexer definition does the trick:

 public class WordCount { private Hashtable m_words; // our indexer; it supports only read ... public int this[ string index ] { get { if ( index.Length ...

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