(a)
Stack s = ...;
foreach(int i in s)
    Console.WriteLine(i);

(b)
Stack s = ...;
IEnumerable enumerable = (IEnumerable) s;
IEnumerator enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext()) {
    int i = (int) enumerator.Current;
    Console.WriteLine(i);
}

Example 7: (a) foreach-style iteration over a collection; (b) the equivalent "by hand" iteration, using the IEnumerable and IEnumerator interfaces.

Back to Article