Monday, June 25, 2007

Indexer in C#

Indexers allow you to index a class or a struct instance in the same way as an array.
The systax is:

[modifier] [return type] this [argument list]
{
get
{
// codes for get accessor
}
set
{
// codes for set accessor
}
}

Here is the C# code:

public class PersonIndexer
{
int[] _age=new int[2];
string[,] _name=new string[2,2];

public int this[int i]
{
get { return _age[i]; }
set { _age[i] = value; }
}
public string this[int i,int j]
{
get { return _name[i, j]; }
set { _name[i, j] = value; }
}
}

static void Main()
{
PersonIndexer Ind = new PersonIndexer();
Ind[0] = 30;
Ind[1] = 40;

Ind[0, 0] = "sanjay";
Ind[0, 1] = "saini";
Ind[1, 0] = "Ram";
Ind[1, 1] = "Kumar";
MessageBox.Show(Ind[0, 0]+ " "+Ind[0, 1]+" is " + Convert.ToString(Ind[0])+" yrs. old.");
MessageBox.Show(Ind[1, 0] + " " + Ind[1, 1] + " is " + Convert.ToString(Ind[1]) + " yrs. old.");
}

Note:

1. If you declare more than one indexer in the same class, they must have different signatures.
2. They can not be static.
3. They can also be inherited.
4. They can be overridden in the derived class and exibit polymorphism.
5. They can be created abstract in the class.

Reference:
http://www.csharphelp.com/archives/archive140.html

No comments: