Sunday, November 14, 2010

Lesson 36 - Indexers

Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties except that their accessors take parameters.

In the following example, a generic class is defined and provided with simple get and set accessor methods as a means for assigning and retrieving values. The class Program creates an instance of this class for storing strings.

class SampleCollection
{
private T[] arr = new T[100];
public T this[int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}

// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args)
{
SampleCollection stringCollection = new SampleCollection();
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}

No comments:

Post a Comment