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

Why Indexer declaration in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your custom objects could be accessed as easily as arrays with just one simple feature?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
public Book GetBookAt(int index) { return books[index]; }
public void SetBookAt(int index, Book book) { books[index] = book; }
After
public Book this[int index] {
  get => books[index];
  set => books[index] = value;
}
What It Enables

Indexer declaration enables your custom classes to be accessed like arrays, making your code simpler and more expressive.

Real Life Example

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.

Key Takeaways

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.