0
0
C Sharp (C#)programming~3 mins

Why Indexer with custom types in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could access your custom objects as easily as array items, but with your own special keys?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
public Book GetBookByISBN(string isbn) { foreach(var book in books) { if(book.ISBN == isbn) return book; } return null; }
After
public Book this[string isbn] { get { return books.FirstOrDefault(b => b.ISBN == isbn); } }
What It Enables

You can access complex collections quickly and clearly using custom keys, just like using an array.

Real Life Example

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.

Key Takeaways

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.