Indexers.md - brainchildservices/curriculum GitHub Wiki

Slide 1

Indexers

What is an indexer?
C# indexers are usually known as smart arrays.
A C# indexer is a class property that allows you to access a member variable of a class using the features of an array.
In C#, indexers are created using this keyword. Indexers in C#

Example1:
We have a Marks class with fields englishMark, scienceMarks and mathsMark that needs to assigned value and retrieve value from another class.
We are writing a program to store values to the fields of the class and then print it
https://dotnetfiddle.net/KiaiDS

Slide 2

Here we have to call each field value. But what if the fields are private which should be the case. One of the options for us is to define the fields are properties.
The next option is for us to use Indexers.

How to declare an Indexer?
image

The return type of the indexer is int because the dealing with fields(englishMark, scienceMarks and mathsMark) that are integers.
The parameter type of the indexer is decided as integer so that we can access each field with an integer index https://dotnetfiddle.net/ZXnRM7
The index values doesn'thave to start at 0. We get to decide what index value points to which field.
https://dotnetfiddle.net/zHOXuy

Slide 3

In the same way, we used an integer to access the fields, we can use string or char or another datatype as index values to access the fields. In this case, the parameter type would change to string or char.
https://dotnetfiddle.net/7jJRMy

Example2:
We have class Temperatue with a public integer array temps. To access the values of the array in another class we have to access the array directly using the object created.
https://dotnetfiddle.net/CeFqha

Slide 3 Downwards

But by creating an indexer, we can access the fields of the array like a array in the other class. https://dotnetfiddle.net/AqOaeV

Difference between Indexers and Properties:
image

References: https://www.youtube.com/watch?v=huqfkUV3Ha8
https://www.c-sharpcorner.com/uploadfile/puranindia/indexers-in-C-Sharp/
https://www.tutorialspoint.com/csharp/csharp_indexers.htm