Simple Numeric Iterator Example C# with Example



Simple Numeric Iterator Example C# with Example

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

IEnumerable is the base interface for all non-generic collections like ArrayList that can be enumerated. 
IEnumerator is the base interface for all generic enumerators like List<>. 
IEnumerable is an interface which implements the method GetEnumerator. The GetEnumerator method returns an 
IEnumerator which provides options to iterate through the collection like foreach. 

0 Comment's

Comment Form