What if your custom objects could be accessed as easily as arrays with just one simple feature?
Why Indexer declaration in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a collection of items, like a list of books, and you want to get or set a book by its position. Without indexers, you must write separate methods like GetBookAt(int index) and SetBookAt(int index, Book book). This feels like using a remote control with too many buttons for simple tasks.
Manually writing methods to access items by position is slow and clunky. It makes your code longer and harder to read. You also lose the natural feeling of using square brackets [] like with arrays. This can cause confusion and mistakes, especially when working with collections often.
Indexer declaration lets you use square brackets [] directly on your class instances to get or set items by index. It makes your class behave like an array or list, making your code cleaner, shorter, and easier to understand. It feels natural and intuitive, just like accessing elements in built-in collections.
public Book GetBookAt(int index) { return books[index]; }
public void SetBookAt(int index, Book book) { books[index] = book; }public Book this[int index] {
get => books[index];
set => books[index] = value;
}Indexer declaration enables your custom classes to be accessed like arrays, making your code simpler and more expressive.
Think of a playlist app where you want to get or change songs by their position. Using an indexer, you can write playlist[2] to get the third song, just like you do with arrays.
Manual methods for indexed access are verbose and unnatural.
Indexer declaration lets you use [] syntax on your own classes.
This makes code cleaner, easier to read, and more intuitive.