Junior — Middle
Can you explain what an indexer is and how it is used in programming?
sobes.tech AI
Answer from AI
An indexer in C# is a special class member that allows objects to be accessed as if they were arrays, meaning accessing elements by index using square brackets [].
An indexer defines get and set methods for accessing elements by key or index, but does not require an explicit method name when called.
Example of using an indexer:
class SampleCollection
{
private string[] data = new string[5];
public string this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
}
// Usage
var collection = new SampleCollection();
collection[0] = "Hello";
Console.WriteLine(collection[0]); // Outputs "Hello"
Indexers make code more readable and convenient, especially when the class represents a collection or set of data.