Simple Numeric Iterator Example

suggest change

A 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);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Iterators:
* Simple Numeric Iterator Example

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
28 Iterators
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script