Indexers are used to access the class members in the same way how we are accessing the array data, that means by providing the index we can read and write to the class members.
Indexers are useful if you want to assign the multiple values to single property in a class. Single property can have multiple properties by using the indexers in C#.
We can create the indexers by using the this keyword in C# as shown below.
using System.Collections;
namespace CSharpIndexerExp
{
class Persons
{
public Hashtable htPersons = new Hashtable( );
public string this[string id]
{
get { return htPersons[id].ToString(); }
set { htPersons[id] = value; }
}
}
}
In the above code we are creating the indexer for HashTable htPersons by using the this keyword in Persons class.
We can access the indexers data like normal arrays in C# by providing the index value as shown below.
using System;
namespace CSharpIndexerExp
{
class Program
{
static void Main(string[] args)
{
Persons obj = new Persons();
//writing data using indexer
obj["A"] = "John";
obj["B"] = "Bob"
//reading data by using indexer
Console.WriteLine("value at key 'A': " + obj["A"]);
Console.Read();
}
}
}
We are assigning the values to the indexer by using keys "A", "B" in the above example and even we are reading the data by providing the same keys.