NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

1.15 Indexers

If properties in C# can be likened to "smart fields", then indexers can be likened to "smart arrays". Whereas properties enable field-like access, indexers enable array-like access.

As an example, consider a ListBox control, which displays strings. This class wants to expose an array-like data structure that exposes the list of strings it contains, but also wants to be able to automatically update its contents when a value is altered. These goals can be accomplished by providing an indexer. The syntax for an indexer declaration is similar to that of a property declaration, with the main differences being that indexers are nameless (the "name" used in the declaration is this, since this is being indexed) and that additional indexing parameters are provided between square brackets.

public class ListBox: Control
{
   private string[] items;
   public string this[int index] {
      get {
         return items[index];
      }
      set {
         items[index] = value;
         Repaint();
      }
   }
}

As with properties, the convenience of indexers is best shown by looking at use rather than declaration. The ListBox class can be used as follows:

ListBox listBox = ...;
listBox[0] = "hello";
Console.WriteLine(listBox[0]);