Start Coding

Topics

C# Indexers: Array-like Access for Objects

Indexers in C# provide a convenient way to access elements of a class or struct using array-like syntax. They enable objects to be treated as arrays, enhancing code readability and flexibility.

What are Indexers?

Indexers allow instances of a class or struct to be indexed just like arrays. They provide a syntax for accessing elements of an object using square brackets [], similar to how you access array elements.

Syntax and Usage

To define an indexer, use the this keyword followed by square brackets. Here's a basic syntax:


public Type this[IndexType index]
{
    get { /* return the value */ }
    set { /* set the value */ }
}
    

Where Type is the return type of the indexer, and IndexType is the type of the index parameter.

Practical Example

Let's create a simple class that uses an indexer to access days of the week:


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

    public string this[int index]
    {
        get
        {
            if (index >= 0 && index < days.Length)
                return days[index];
            else
                return "Invalid day";
        }
    }
}

// Usage
WeekDays week = new WeekDays();
Console.WriteLine(week[3]); // Output: Thursday
    

Multiple Parameters

Indexers can also accept multiple parameters, allowing for more complex access patterns:


public class Matrix
{
    private int[,] data = new int[3, 3];

    public int this[int row, int col]
    {
        get { return data[row, col]; }
        set { data[row, col] = value; }
    }
}

// Usage
Matrix matrix = new Matrix();
matrix[1, 2] = 5;
    

Best Practices and Considerations

  • Use indexers when your class represents a collection or has array-like behavior.
  • Ensure proper bounds checking to avoid exceptions.
  • Consider using properties instead if you're only accessing a single element.
  • Indexers can be overloaded with different parameter types, similar to method overloading.

Advanced Features

C# also supports more advanced indexer features:

  • Read-only indexers (omit the set accessor)
  • Write-only indexers (omit the get accessor, though rarely used)
  • Interface indexers for implementing indexers in interfaces

Conclusion

Indexers in C# provide a powerful way to create objects that can be accessed like arrays. They enhance code readability and offer flexible access patterns for your custom types. By mastering indexers, you can create more intuitive and efficient APIs for your classes and structs.

Remember to use indexers judiciously and consider the nature of your data and how it will be accessed. When used appropriately, indexers can significantly improve the usability of your C# code.