Tuesday, March 23, 2010

Indexers

Using indexers, we can treat classes as if they were arrays or collections; that is, we can access the indexer’s elements by using square brackets ([]).  An indexer is similar to properties in that it also uses the accessors get and set to express its characteristics.
The declaration of the indexer takes the form:
indexer  - type this [parameter – type parameter]
{
    get {};
    set {};
}
Where:
indexer – type is the type of the indexer.
parameter – type is the type of the parameter.
parameter is a parameter or a parameter list.
The keyword this points to the object to which the indexer belongs.
Although the indexer doesn’t have a name, it is recognized by its signature (types and number of parameters). It is possible to modify the indexer declaration with the keyword new or one of the access modifiers.
In the following example, we declare an array and an indexer of the type string. Then the indexer is used to access the elements of the object as if they were array elements.
//Example 6.8.cs
//Indexer example
using System;
class MyClass
{
    private string[] myArray = new string[10];
    //Indexer declaration:
    public string this[int index]
    {
        get
        {
            return myArray[index];
        }
        set
        {
            myArray[index] = value;
        }
    }
}
public class MainClass
{
    public static void Main()
    {
        MyClass s = new MyClass();
        //Using the indexer to initialize the element #1 and #2:
        s[1] = “Tom”;
        s[2] = “Edison”;
        for ( int i = 0; i<5; i++)
        {
            Console.WriteLine(“Element #{0}={1}”, i, s[i]);
        }
   
    }
}
Notes on using indexers:
•    It is common to use the accessors set and get in inspecting the limits of the indexer to avoid errors.  For example:
if(!(index < 0 || index >= 10))
//…
•    It is possible for interfaces to have indexers. They are declared in the same way with the following exceptions:
o    Interface indexers don’t use modifiers.
o    There is no implementation of accessors in interfaces.
The following is an example of an interface indexer:
string this [int index]
{
    get;
    set;
}

No comments:

Post a Comment