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:

image

Because indexing operates on the object directly, there’s no member name involved. In fact, from the receiving end’s point of view, the left side of the indexing operation is nothing but the object itself, hence this. To define the first indexers taking in an integer parameter, you therefore write the following:

There are different ways to look at it. One is to see the indexer as ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.