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.
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.
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.
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
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;
C# also supports more advanced indexer features:
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.