An indexer is a property that enables objects to be indexed and accessed using square bracket notation, providing a mechanism to retrieve or set values based on specified parameters.
(āĻā§āϞāĻžāϏā§āϰ āĻāϞāĻŋāĻŽā§āύā§āĻāĻā§ āĻā§āϝāĻžāϰā§āϰ āĻŽāϤ⧠āĻŦā§āϝāĻŦāĻšāĻžāϰ āĻāϰāϤ⧠āĻĻā§ā§)āĨ¤
Indexers provide a way to access elements of a collection or class as if they were arrays, enabling convenient and intuitive access to internal data structures without exposing them directly.
You would use an indexer instead of directly using an array when you want to encapsulate the data structure within a class, providing controlled access and potentially adding additional functionality or validation beyond simple array access.
public class MyCollection
{
private int[] data = new int[10];
// Indexer definition
public int this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
}
class Program
{
static void Main()
{
MyCollection collection = new MyCollection();
// Using the indexer to set and retrieve values
collection[0] = 42;
int value = collection[0];
Console.WriteLine($"Value at index 0: {value}");
}
}