ECMA-334: 26. Iterators
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| C# Language Specification |
| © 2006 ECMA International |
26. Iterators
An iterator is a means of implementing a function member whose return type is an enumerator interface or enumerable interface. The function member returns the ordered sequence of values as yielded by the iterator.
[Example: The following Stack<T> class implements its GetEnumerator method using an iterator. The
iterator enumerates the elements of the stack in top to bottom order.
using System.Collections.Generic; public class Stack<T>: IEnumerable<T> { T[] items; int count; public void Push(T data) {…} public T Pop() {…} public IEnumerator<T> GetEnumerator() { for (int i = count – 1; i >= 0; --i) { yield return items[i]; } } }
Iterators are implemented using yield statements, which can only be used in methods whose return type is
an enumerator interface. The presence of the GetEnumerator method makes Stack<T> an enumerable
type, allowing instances of Stack<T> to be used in a foreach statement. The following example pushes
the values 0 through 9 onto an integer stack and then uses a foreach loop to display the values in top to
bottom order.
using System; class Test { static void Main() { Stack<int> s = new Stack<int>(); for (int i = 0; i < 10; i++) s.Push(i); foreach (int i in s) Console.Write("{0} ", i); Console.WriteLine(); } }
The output of the example is:
9 8 7 6 5 4 3 2 1 0
end example]