- C# Indexers Introduction
- C# Indexers
The book Illustrated C# 7, Fifth Edition by Daniel Solis and Cal Schrotenboer published by Apress has a discussion of indexers on page 162. Indexers are similar to how arrays work.
string str = null; Console.WriteLine(str?[0]); // Writes nothing; no error. Console.WriteLine(str[0]); // NullReferenceException To write an indexer, define a property called this, specifying the arguments in square brackets. class Sentence { string[] words = "The quick brown fox".Split(); //field public Sentence() { } // default constructor public Sentence(string str) // constructor { words = str.Split(); } public int Length // property { get { return words.Length; } } public string this[int wordNum] // indexer { get { return words[wordNum]; } set { words[wordNum] = value; } } } static void Main(string[] args) { string s = "hello world"; Console.WriteLine(s[0]); // 'h' zero-based Console.WriteLine(s[5]); // ' ' string str = null; Console.WriteLine(str?[0]); // Writes nothing; no error. // Console.WriteLine(str[0]); // NullReferenceException Sentence sen = new Sentence(); Console.WriteLine(sen[1]); // quick sen[3] = "wildebeest"; // replace the 4th word Console.WriteLine(sen[3]); // wildebeest for (int i=0;i<sen.Length;i++) { Console.Write(sen[i] + "|"); } // now use our constructor to use our sentence Sentence sent = new Sentence("The sleeping black cat"); Console.WriteLine(sent[1]); // sleeping }