First, let's talk about indexer. Class (or struct) instances can be indexed like array elements thanks to a highly specialised attribute called the indexer (properties can be static but indexers cannot).
Now, why should you use indexer
- The class becomes the data structure instead of the new data structure
- Syntax is easy
With that said, when shoule you use indexer? If your class requires list or arrays of its instances. Here's a code to show this
public class Person{
public string Name{get; set;}
private Person[] _backingStore;
public Person this[int index]
{
get{
return _backingStore[index];
}
set{
_backingStore[index] = value;
}
}
}
Person p = new Person();
p[0] = new Person(){Name = "Bostov"};
p[1] = new Person(){Name = "Mindy Tow"};