O'Reilly logo

Illustrated C# 2008 by Daniel Solis

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

Chapter 20. Enumerators and Iterators

Enumerators and Enumerable Types

In Chapter 14, you saw that you can use a foreach statement to cycle through the elements of an array. In this chapter, you'll take a closer look at arrays and see why they can be processed by foreach statements. You'll also look at how you can add this capability to your own user-defined classes. Later in the chapter, I'll discuss the use of iterators.

Using the foreach Statement

When you use the foreach statement with an array, the statement presents you witheach element in the array, one by one, allowing you to read its value.

For example, the following code declares an array with four elements, and then uses a foreach loop to print out the values of the items:

int[] arr1 = { ...

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