Monday, March 17, 2008

C# indexer

Declaration:
public this [ identifier]

Example:
public string this [int theIndex]



Sample C# Use:

using System;

//Indexer Class Declaration
class MyIntIndexer
{
private string[] theData;

public MyIntIndexer(int size)
{
theData= new string[size];

//Initialize
for (int i=0; i < size; i++)
{
theData[i] = "nothing";
}
}

public string this[int position]
{
get
{
return theData[position];
}
set
{
theData[position] = value;
}
}


static void Main(string[] args)
{
int size = 5;

MyIntIndexer myIndexer = new MyIntIndexer(size);

myIndexer[3] = "str3";
myIndexer[1] = "str1";
myIndexer[5] = "str5";

}
}

No comments: