CSharp examples for Custom Type:Indexer
Indexers provide a syntax for accessing elements in a class or struct which has a list or dictionary of values.
Indexers are similar to properties and are accessed via an index argument rather than a property name.
The string class has an indexer to access each of its char values via an int index:
using System;// ww w. j a v a2 s. com class Test { static void Main(){ 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(s) can be of any type(s).
Indexers have the same modifiers as properties.
Indexers can be called null-conditionally by inserting a question mark before the square bracket
using System;/*from w w w.j a v a 2 s. c om*/ class Test { static void Main(){ string s = null; Console.WriteLine (s?[0]); // Writes nothing; no error. } }