O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

One feature you may want to provide is to allow users of your collection to add to or extract from the collection with an indexer, just as is done with arrays.

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 if the ListBox itself were an array.[10] For example, such a property would permit statements such as the following:

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

An indexer is a C# construct that allows you to treat a class as if it were an array. In the preceding example, you are treating the ListBox as if 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;}

The return type determines the type of object that will be ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required