- Indexer allows instance of a class or structure to be indexed as array.
- The main use of indexers is to support the creation of specialized arrays that are subject to one or more constraints.
- Indexer is very similar to Properties but properties are used for return or set the specific data member but an Indexer return or set the particular value from the object instances.
- As Properties are accessed through simple name but Indexer is accessed through an index.
- The basic syntax of Indexer is shown below:
// The get accessor.
// return the value specified by index
// The set accessor.
// set the value specified by index
element type: Here element type is element type of Indexer, Thus, each element accessed by the indexer will be of type element-type. It corresponds to the element type of an array.Parameter ‘index’:The parameter index receives the index of the element being accessed.get:It is a accessor which return the value specified by the index.Set:It is a accessor that set the value specified by the index.
Here is an example of Indexer which is sufficient to understand the concept of Indexer:
string values = new string;//backing store
public string this[int number]
//this is invoked when object of student_name class access with 
return values[number];//if bound in the range
//this is invoked when obejct of student_name class assigned with 
values[number]=value;//assign the element store in internal array
static void Main()
//create new objects and assign values through Indexer
student_name name = new student_name();
name = "Radha";
name = "Error";
//read elements through the indexer
string name_value1 = name;
string name_value2 = name;
string name_value3 = name;
string name_value4 = name;
string name_value5 = name[-1];
//write the result
This program includes a student_name class with an indexer we define. The student_name class contains an indexer that has get and set method bodies. These accessors have logic that ensures the Array will not be accessed out-of-bounds. The output of the above program will be as follows:
Precautions while using Indexers
- An indexer does not define a storage location, so a value produced by an indexer cannot be passed as a ref or out parameter to a method.
- An indexer cannot be declared static.