Thursday, August 13, 2009

Indexer

Define:
Indexer enable class/struct instance to be index, just as user can index an array to store/retrieve data. Example
arr[0]=”C#”;
string str=arr[0];
Indexing is the mechanism to travel on each collection index position. Indexing also allow user to store/retrieve data based on specific index position (as show above). Earlier user were restricted to index only to array, but in .Net framework 2.0 and above user can index even to user-define type.

Example:


Above class is based on generics mechanism. You can find more details on generics over here. We define Collection1 class and allow user to index on Collection1 class (as shown in Program class below).

Indexer is similar to class property where property has 'get' and 'set' accessor. 'get' accessor will be little bit different from normal 'get' accesssor. In indexer 'get' accessor will return array index to the position as define by user. So, in this case we are returning arr[i] in 'get' accessor for each request.

To define index on your class instance, property name must be this keyword. As this keyword points to class instance, we need to make this keyword as a property name.


Notethis property return type is T which point to generic type. i.e. whatever type user define during class instantiation (string type as show below), the same type T will refer.

In above example, we create class instance with string data type, hence indexer will store/retrieve string data type based on given index position.

Some more information:

String Indexer: User can also index with string rather than integer. Example arr["bill gates"]="MICROSOFT";

Two-dimension Indexer: User can also declare more than one parameter in declaring index. Example arr["bill"]["gates"]="MICROSOFT";

Indexer in Interface: User can also include indexer in interface. Example

public interface IInterface
{
string this[i]
{
get;
set;
}
}

------------------------------------------------------------------------------------------------------------------------------

Hope users - you like the article. If not than please leave your comments/query.