Indexers with examples.
Notes from this video:
Indexer:
An indexer allows us to treat an object like an array. It provides a way to access elements in an object using array-like syntax.
Indexers are defined using the this keyword followed by an index parameter.
Ex: -
public class MyClass
{
private int[] myArray = new int[5];
public int this[int index]
{
get { return myArray[index]; }
set { myArray[index] = value; }
}
}
Use Case
Scenario: Imagine we have a class that holds grades for students. We want to access the grades using array-like syntax.
Implementation:
public class Grades
{
private int[] grades = new int[5];
public int this[int index]
{
get { return grades[index]; }
set { grades[index] = value; }
}
}
// Usage
Grades studentGrades = new Grades();
studentGrades[0] = 85;
studentGrades[1] = 90;
Console.WriteLine(studentGrades[0]); // Output: 85
Console.WriteLine(studentGrades[1]); // Output: 90
In this example, studentGrades[0] accesses the first grade, studentGrades[1] accesses the second grade, and so on.
The indexer allows the Grades class to be used like an array for storing and retrieving grades.
Multi-Dimensional Indexers
C# also supports multi-dimensional indexers, allowing you to define indexers with multiple parameters:
public class Matrix
{
private int[,] data = new int[3, 3];
public int this[int row, int column]
{
get
{
return data[row, column];
}
set
{
data[row, column] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Matrix matrix = new Matrix();
// Using the indexer to set values
matrix[0, 0] = 1;
matrix[1, 1] = 2;
matrix[2, 2] = 3;
// Using the indexer to get values
Console.WriteLine(matrix[0, 0]);
Console.WriteLine(matrix[1, 1]);
Console.WriteLine(matrix[2, 2]);
}
}