Creating Your Own Collections

The goal in creating your own collections is to make them as similar to the standard .NET collections as possible. This reduces confusion, and makes for easier-to-use classes and easier-to-maintain code.

Creating Indexers

One feature you should provide is to allow users of your collection to add to or extract from the collection with an indexer, just as you would do with an array.

For example, suppose you create a ListBox control named myListBox that contains a list of strings stored in a one-dimensional array, a private member variable named myStrings. A ListBox control contains member properties and methods in addition to its array of strings, so the ListBox itself is not an array. However, it would be convenient to be able to access the ListBox array with an index, just as though the ListBox itself were an array.[4] For example, such a property would let you do things like this:

string theFirstString = myListBox[0];
string theLastString = myListBox[Length-1];

An indexer is a C# construct that allows you to treat a class as though it were an array. In the preceding example, you are treating the ListBox as though it were an array of strings, even though it is more than that. An indexer is a special kind of property, but like all properties, it includes get and set accessors to specify its behavior.

You declare an indexer property within a class using the following syntax:

type this [type argument]{get; set;}

For example:

public string this[int index] { get ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.