What if you could access your custom objects as easily as array items, but with your own special keys?
Why Indexer with custom types in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a collection of custom objects, like books or products, and you want to access them quickly using a special key, such as a unique ID or a combination of properties.
Without indexers, you would have to write long methods to search through the collection every time you want to find an item.
Manually searching through collections is slow and repetitive. You might write similar code again and again, increasing the chance of mistakes.
It also makes your code messy and hard to read, especially when you want to access items like they were in an array.
Using an indexer with custom types lets you access your objects using a simple, array-like syntax but with your own keys.
This makes your code cleaner, faster to write, and easier to understand, because you can use meaningful keys instead of just numbers.
public Book GetBookByISBN(string isbn) { foreach(var book in books) { if(book.ISBN == isbn) return book; } return null; }public Book this[string isbn] { get { return books.FirstOrDefault(b => b.ISBN == isbn); } }You can access complex collections quickly and clearly using custom keys, just like using an array.
Think of a library system where you want to get a book by its ISBN code directly, instead of searching through all books manually every time.
Manual searching is slow and error-prone.
Indexers let you use custom keys to access data easily.
This makes your code cleaner and more intuitive.