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 ...

Get C# Primer: A Practical Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.