What are indexers in C#

In C#, an indexer is a special member of a class that allows objects of that class to be indexed just like arrays. It provides a way to access elements or values within an object using an index or a key. Indexers are similar to properties, but instead of accessing a single value, they provide access to multiple values or elements based on an index or key.

Indexers

Indexers are defined using the this keyword, followed by the indexer parameter type and name within square brackets. They can be used with one or multiple parameters, depending on the requirements of the class. The parameters define the keys or indices used to access specific elements or values.

public class MyClass { private string[] data = new string[5]; public string this[int index] { get { if (index >= 0 && index < data.Length) return data[index]; else throw new IndexOutOfRangeException("Index is out of range"); } set { if (index >= 0 && index < data.Length) data[index] = value; else throw new IndexOutOfRangeException("Index is out of range"); } } }

Usage:

MyClass myObject = new MyClass(); myObject[0] = "Value 1"; myObject[1] = "Value 2"; string value1 = myObject[0]; string value2 = myObject[1];

In this example, the MyClass class defines an indexer that allows accessing elements of the data array using an index. The indexer is defined with the this keyword and an integer parameter index. The get accessor retrieves the value at the specified index, while the set accessor sets the value at the specified index.

The usage of the indexer is similar to accessing elements of an array. You can assign values to the indexer using the assignment operator (=) and retrieve values by accessing the indexer with the desired index.

Conclusion

Indexers provide a convenient way to access data or elements within an object, making the object behave like an array or a collection with custom indexing logic. They can be used to enhance the usability and readability of a class, especially when dealing with complex data structures or custom collections.