Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Enumerators and foreach

The C# compiler automatically generates code to use an enumerator when the foreach statement is used. Thus, given an object c that is an instance of a concrete class SomeContainer that implements the Container interface, we can use the foreach statement to enumerate the objects in the container as follows:

Container c = new SomeContainer();
// ...
foreach (object obj in c)
{
    Console.WriteLine(obj);
}


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.