C Sharp

Defining Indexers

Because properties are sometimes referred to as "smart fields" and indexers are called "smart arrays," it makes sense that properties and indexers would share the same syntax. Indeed, defining indexers is much like defining properties, with two major differences: First, the indexer takes an index argument. Second, because the class itself is being used as an array, the this keyword is used as thename of the indexer. You'll see a more complete example shortly, but take a look at an example indexer: -

class MyClass
{
    public object this [int idx]
    {
        get
        {
            // Return desired data.
        }
        set
        {
            // Set desired data.
        }
    }
    ...
}

I haven't shown you a full example to illustrate the syntax of indexers because the actual internal implementation of how you define your data and how you get and set that data isn't relevant to indexers. Keep in mind that regardless of how you store your data internally (that is, as an array, a collection, and so on), indexers are simply a means for the programmer instantiating the class to write code such as this: -

MyClass cls = new MyClass();
cls[0] = someObject;
Console.WriteLine("{0}", cls[0]);

What you do within the indexer is your own business, just as long as the class's client gets the expected results from accessing the object as an array.