C#.Net Indexer

An Indexer is a special type of property that allows a class or structure to be accessed the same way as array for its internal collection. You can then access the instance of this class using the array operator[ ].

Declaration of an indexer is similar to a property. Like properties, you have get and set accessors for defining an indexer. However, properties return or set a specific data member, whereas indexers returns or sets a particular value from the object instance. In other words, it breaks the instance data into smaller parts and indexes each part, gets or sets each part.

Defining a property involves providing a property name. Indexers are not defined with names, but with this keyword, which refers to the object instance.

Example 1: Demonstrates the concept of Indexer

class ex_indexer
{
    private string[] name = new string[10];
    public string this[int index]
    {
        get
        {
            string s = name[index];
            return s;
        }
        set
        {
            name[index] = value;
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        ex_indexer obj = new ex_indexer();
        obj[0] = "C# Programming";
        obj[1] = "C-Sharp Programming";
        for(int i = 0;i<=9;i++)
        {
            Console.WriteLine(obj[i]);
        }
        Console.ReadKey();
    }
}