CSharp/C# Tutorial - C# Indexers

Indexers provide an array-like syntax for accessing elements in a class or struct.

Indexers are similar to properties, but are accessed via an index argument rather than a property name.

The string class has an indexer that lets you access each of its char values via an int index:

string s = "hello"; 
Console.WriteLine (s[0]); // 'h' 
Console.WriteLine (s[3]); // 'l' 

The syntax for using indexers is like that for using arrays, except that the index argument can be of any type.

Indexers have the same modifiers as properties.

Implementing an indexer

To write an indexer, define a property called this, specifying the arguments in square brackets.

For instance:

class MyWord { //w w w .j  ava  2s.c  om
   string[] words = "this is a test".Split(); 
   public string this [int wordNum] // indexer 
       get { 
           return words [wordNum]; 
       set { 
           words [wordNum] = value; 

Here's how we could use this indexer:

MyWord s = new MyWord(); 
Console.WriteLine (s[3]);
s[3] = "CSS"; 
Console.WriteLine (s[3]); // CSS

A type may declare multiple indexers, each with parameters of different types.

An indexer can also take more than one parameter:

public string this [int arg1, string arg2] {
    get { ... } set { ... } 

If you omit the set accessor, an indexer becomes read-only.