What is an indexer, and how does it let a custom class support square-bracket syntax like an array?
Short answer
An indexer is a special property-like member defined with 'this[...]' syntax, letting instances of your class be accessed using square brackets (obj[key]) just like an array or dictionary — you define get/set accessors just as with a normal property.
Advertisement
AModel answer
An indexer is a special property-like member defined with 'this[...]' syntax, letting instances of your class be accessed using square brackets (obj[key]) just like an array or dictionary — you define get/set accessors just as with a normal property.
public class WeekSchedule {
private readonly string[] _days = new string[7];
public string this[int dayIndex] {
get => _days[dayIndex];
set => _days[dayIndex] = value;
}
}
var schedule = new WeekSchedule();
schedule[0] = "Meeting";
Console.WriteLine(schedule[0]); // "Meeting"Real-world example
Building a custom collection-like class (e.g., a Matrix or Grid) that should support natural array-style access syntax.
Likely follow-ups
- Can an indexer accept a non-integer parameter type, like a string, the way Dictionary does?
Related topics