Closely related to properties are indexers. Both classes and structs can contain just one indexer, which is best described as a parameterized property that can be invoked by using an indexing expression. The stereotypical example of an indexer is on a vector object or a dictionary collection. Let’s first show how the latter is used on the generic Dictionary type defined in System.Collections.Generic and then move on to defining our own Vector type with an indexer:

var phoneBook = new Dictionary<string, int>();phoneBook["Bart"] = 51662;phoneBook["John"] = 96207;Console.WriteLine("Bart's phone number is: " + phoneBook["Bart"]);

The second and third lines add entries to the dictionary by passing the intended ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.