CHAPTER 18

image

Indexers, Enumerators, and Iterators

It is sometimes useful to be able to treat an object as if it were an array and access it by index. This can be done by writing an indexer for the object. In the same way that a property looks like a field but has accessors to perform get and set operations, an indexer looks like an array but has accessors to perform array-indexing operations.

Pretty much every object with an indexer will also have an enumerator. Enumerators and iterators provide two ways of returning a sequence of values from an object.

Indexing with an Integer Index

A class that contains a database row might implement an indexer ...

Get A Programmer's Guide to C# 5.0, 4th Edition 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.