Simple Numeric Iterator Example
suggest changeA common use-case for iterators is to perform some operation over a collection of numbers. The example below demonstrates how each element within an array of numbers can be individually printed out to the console.
This is possible because arrays implement the IEnumerable
interface, allowing clients to obtain an iterator for the array using the GetEnumerator()
method. This method returns an enumerator, which is a read-only, forward-only cursor over each number in the array.
int[] numbers = { 1, 2, 3, 4, 5 };
IEnumerator iterator = numbers.GetEnumerator();
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current);
}
Output
1
2
3
4
5
It’s also possible to achieve the same results using a foreach
statement:
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents