O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

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

Indexers

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 ...

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