C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
IEnumerator: With GetEnumerator, it becomes possible to write methods that act on the IEnumerator interface.
Info: IEnumerator is not the same as IEnumerable. It is an interface implemented by Enumerator objects.
Loops: IEnumerable is a collection that can be looped over with foreach-loops. This is how it is usually used.
ForeachC# program that uses GetEnumerator
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(9);
List<int>.Enumerator e = list.GetEnumerator();
Write(e);
}
static void Write(IEnumerator<int> e)
{
while (e.MoveNext())
{
int value = e.Current;
Console.WriteLine(value);
}
}
}
Output
1
5
9
Thus: We only have to have one Write method to handle all generic enumerators that handle integers.