Defining Indexers

To define an indexer, you use the this keyword in yet another context. Take a moment to think back about all the allowed uses of this you’ve seen so far. To see why the this keyword is used in this context, take a closer look at the following code:

Vector victor = new Vector(1, 2, 3);Console.WriteLine("X = " + victor[0]);// We're leaving the implementation of an indexer with a string-typed parameter// as an exercise for the reader. (See the next code fragment.)Console.WriteLine("Y = " + victor["y"]);Console.WriteLine("Z = " + victor[2]);

Because indexing operates on the object directly, no member name is involved. In fact, from the receiving end’s point of view, the left side of the indexing operation ...

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.