Introduction
An indexer in C# allows instances of a class or struct to be indexed like arrays. This means you can access elements using array-like syntax without explicitly specifying a type or instance member. Indexers are defined using this keyword, and they can have both get and set accessors.
Here’s a simple example.
public class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get => arr[i];
set => arr[i] = value;
}
}
In this example, SampleCollection is a generic class with an indexer that allows you to get and set elements using an index, just like an array12.Example.
This example demonstrates a simple string collection with an indexer.
public class StringCollection
{
private string[] strings = new string[10];
public string this[int index]
{
get => strings[index];
set => strings[index] = value;
}
}
You can use this class like an array.
var collection = new StringCollection();
collection[0] = "Hello";
collection[1] = "World";
collection[2] = "My name is Arpit";
Console.WriteLine($"{collection[0]} {collection[1]}, {collection[2]}"); // Output: Hello World, My name is Arpit
The output will be,