0
0
CsharpConceptBeginner · 3 min read

What is Indexer in C#: Simple Explanation and Example

An indexer in C# allows an object to be accessed like an array using square brackets []. It lets you define how to get or set values by an index inside your class, making your objects behave like collections.
⚙️

How It Works

Think of an indexer as a special door on your class that lets you use square brackets [] to get or set values, just like you do with arrays or lists. Instead of calling a method, you simply use an index to access data inside your object.

Behind the scenes, the indexer is a pair of methods: one to get a value and one to set a value, both using an index parameter. This makes your class feel natural and easy to use when you want to work with a collection of items stored inside it.

💻

Example

This example shows a simple class WeekDays that stores names of days and lets you access them by index using an indexer.

csharp
using System;

class WeekDays
{
    private string[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

    public string this[int index]
    {
        get { return days[index]; }
        set { days[index] = value; }
    }
}

class Program
{
    static void Main()
    {
        WeekDays week = new WeekDays();
        Console.WriteLine(week[1]);  // Access Monday
        week[1] = "Mon";            // Change Monday to Mon
        Console.WriteLine(week[1]);  // Access updated value
    }
}
Output
Monday Mon
🎯

When to Use

Use an indexer when you want your class to act like a collection or array, so users can access elements easily with an index. This is helpful when your class holds a list, array, or any group of items internally.

For example, you might create a class for a custom list of products, settings, or calendar days, and let users get or set items by number without calling special methods. It makes your code cleaner and more intuitive.

Key Points

  • An indexer lets you use [] on objects like arrays.
  • It uses get and set accessors with an index parameter.
  • Indexers improve code readability and usability for collection-like classes.
  • You can define indexers with different parameter types, not just integers.

Key Takeaways

An indexer lets you access class data using square brackets like an array.
It simplifies working with collection-like classes by hiding method calls.
Indexers use get and set accessors with an index parameter.
They make your class easier and more natural to use.
You can customize indexers with different index types.