Updated on Kisan Patel
Indexers can be termed as location indicators and they are used to access class objects in the same way as array elements are accessed.
You can define indexer by using the this keyword, which refers to the object instance.
The syntax for declaring an indexer:
<access modifier> <Return Type> this[argument list] { get { //code for get } set { //code for set } }
Let’s take one example to understand how indexers in C# works.
using System; namespace ConsoleApp { class List { string[] namelist = new string[3]; public string this[int index] { get { if (index < 0 || index >= namelist.Length) { throw new Exception("Index out of range."); } else { return (namelist[index]); } } set { namelist[index] = value; } } } class Tester { public static void Main(string[] args) { List list = new List(); list[0] = "Kisan"; list[1] = "Devang"; list[2] = "Ravi"; for (int i = 0; i <= 2; i++) Console.WriteLine(list[i]); } } }
Here is the output of the above C# program…
This program includes a List class with an indexer we define. The Layout class contains an indexer that has get and set method bodies. These accessors have logic that ensures the array will not will be accessed out-of-bounds.