Indexers in C# offer a way to use instances of classes like arrays. They allow the use of square bracket operators, []
, to read members of class instances.
To use indexers, you first have to define them:
// Defining Node for Linked Listclass Node {public int data;public Node next;public Node(int d) {data = d;next = null;}}// Defining Linked Listclass LinkedList {Node head;// Setting up indexerspublic int this[int i]{// get indexer allows square brackets to read dataget => this.getAt(i);// set indexer allows square brackets to change dataset => this.setAt(i, value);}// Function defined for indexerpublic void setAt(int i, int value){int count = 0;Node temp = this.head;while (i > count){if (temp.next != null){temp = temp.next;count++;}else if (i != count){throw new System.ArgumentException("Out of bound element accessed");}}temp.data = value;}// Function defined for indexerpublic int getAt(int i){int count = 0;Node temp = this.head;while (i > count){if (temp.next != null){temp = temp.next;count++;}else if (i != count){throw new System.ArgumentException("Out of bound element accessed");}}return temp.data;}// The following functions give basic functionality// to the Linked Listpublic void pushBack(int new_data){Node new_node = new Node(new_data);if (this.head == null) {this.head = new_node;return;}Node temp = this.head;while (temp.next != null) {temp = temp.next;}Node lastNode = temp;lastNode.next = new_node;}public void pop(){this.head = this.head.next;}}class HelloWorld{static void Main(){// Setting up Linked ListLinkedList list = new LinkedList();list.pushBack(10);list.pushBack(20);// Accessing data using indexersSystem.Console.WriteLine(list[0]);System.Console.WriteLine(list[1]);// Changing data using indexerslist[1] = 15;System.Console.WriteLine(list[1]);}}
This example demonstrates how the indexers can be set up and used for a Linked List.
The indexers are set up at the start of the LinkedList
class. The function defining the indexers is written as this[int i]
, implying that it will be called with an integer inside square brackets following the variable name. The get
keyword defines which value it will return if the indexer is used for this purpose. In this case, it calls the getAt()
function. The set
keyword defines how to change a value if indexers are used with the assignment operator (=
). Here, it calls the setAt()
function, which sets the value.
The indexers are set up to both read and write data to the Linked List. Two read options are done on lines 87, 88, and 92 with list[0]
and list[1]
inside the print statements. These indexer expressions inside the print statements access the first and second elements inside the linked list from the head. One set operation is done on line 91 with line[1] = 15
. This command changes the value of the second node from the head to 15.
Free Resources