With indexers you can access elements in a class or struct that encapsulate a list or dictionary of values. Accessed via index argument.

Example: String class has an indexer.

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

Can be called on null-conditional

string s = null;
Console.WriteLine (s?[0]); // Writes nothing; no error.

Implementing an indexer

You need to define property called this.

class Sentence
string[] words = "The quick brown fox".Split();
public string this [int wordNum] // indexer
get { return words [wordNum]; }
set { words [wordNum] = value; }

Sentence s = new Sentence();
Console.WriteLine (s[3]); // fox
s[3] = "kangaroo";
Console.WriteLine (s[3]); // kangaroo

Leave a Reply

Your email address will not be published. Required fields are marked *