Understanding Indexer Methods

The C# language provides the capability to design custom classes and structures that may be indexed just like a standard array, by defining an indexer method. This feature is most useful when you are creating custom collection classes (generic or nongeneric).


Lets your class use [] syntax like an array.

Define this[param] with get/set.


class BeaconList
 {
     private string[] _beacons = new string[5];
     // this[] = indexer definition
     public string this[int index]
     {
         get => _beacons[index];
         set => _beacons[index] = value;
     }
 }
 
BeaconList list = new BeaconList();
list[0] = "1.1.1.1";
list[1] = "10.10.10.5";
Console.WriteLine(list[0]);


String Indexer

class Config
 {
     private Dictionary<string, string> _settings = new();
     public string this[string key]
     {
         get => _settings[key];
         set => _settings[key] = value;
     }
 }
 
Config cfg = new Config();
cfg["sleep"] = "20";
cfg["jitter"] = "15";
Console.WriteLine(cfg["sleep"]);


Overloaded Indexers

class AgentStore
 {
     private List<Agent> _agents = new List<Agent>();
     // access by index
     public Agent this[int index]
     {
         get => _agents[index];
     }
     // access by hostname
     public Agent this[string hostname]
     {
         get => _agents.FirstOrDefault(x => x.Host == hostname);
     }
 }
 
var store = new AgentStore();
var agent1 = store[0]; // by index
var agent2 = store["DC01"]; // by hostname
 
/* 
Property -> obj.Name (single value)
Indexer -> obj[0] (element in collection)
    Uses this[param] with get/set, just like a property
    Can overload with different param types (int,string,etc.)
 */