Indexers
An indexer provides a way to access an object via an index like array. For instance, if we define an indexer for a class, that class works similarly to an array. This means the collection of this class can be accessed by index.
Note
Keywordthis
is used to define an indexer. The main benefit of indexer is that we can set or retrieve the indexed value without explicitly specifying a type.
Consider the following code snippet:
public class PersonCollection { private readonly string[] _persons = Persons(); public bool this[string name] => IsValidPerson(name); private bool IsValidPerson(string name) => _persons.Any(person => person == name); private static string[] Persons() => new[] {"Shivprasad","Denim","Vikas","Merint","Gaurav"}; }
The preceding code is a simpler one to represent the power of an indexer. We have a PersonCollection
class having an indexer that makes this class accessible via indexer. Please refer to the following code:
private static void...