To write an indexer, define a property called this and then set the arguments in square brackets.
class WordList{ string[] words = "this is a test from book2s.com".Split(); public string this [int wordNum] // indexer { get { return words [wordNum]; } set { words [wordNum] = value; } } }
Here's how we could use this indexer:
WordList s = new WordList(); Console.WriteLine (s[3]); s[3] = "abc"; Console.WriteLine (s[3]);
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 { ... } }
Omitting the set accessor makes an indexer read-only.
You can use expression-bodied syntax in indexer.
public string this [int wordNum] => words [wordNum];
using System; class MainClass//from ww w . j av a 2s. c om { public static void Main(string[] args) { WordList s = new WordList(); Console.WriteLine (s[3]); s[3] = "abc"; Console.WriteLine (s[3]); } } class WordList{ string[] words = "this is a test from book2s.com".Split(); public string this [int wordNum] // indexer { get { return words [wordNum]; } set { words [wordNum] = value; } } }