IEnumerator<T>
Learn the iterator mechanism with IEnumerator<T>.
The IEnumerator<T> interface
IEnumerator<T> is the lower layer of iteration. It has three members: MoveNext() advances to the next item and returns a bool; Current gives the current item; Reset() returns to the start.
Before the first MoveNext() call Current is undefined. When the sequence ends MoveNext() returns false. Using this interface directly reveals what foreach hides.
How foreach works
foreach (var x in seq) does the following: it calls seq.GetEnumerator(), then in each step calls MoveNext() and reads Current. The loop ends when MoveNext returns false.
If the iterator implements IDisposable, foreach calls Dispose at the end. The same cleanup happens when you open it manually with using. Direct IEnumerator use is rare; foreach usually suffices.
Exercise Use an iterator by hand
Get an iterator from list below with GetEnumerator(). Use MoveNext() and Current to print the first two items on separate lines with Console.WriteLine.
Show example solution
Get the iterator with var e = list.GetEnumerator(); Call e.MoveNext(); + Console.WriteLine(e.Current); twice.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List<int> { 10, 20, 30 };
var e = list.GetEnumerator();
e.MoveNext();
Console.WriteLine(e.Current);
e.MoveNext();
Console.WriteLine(e.Current);
}
}
Test yourself
-
Complete the MoveNext call
while (e.____())Show answer
while (e.MoveNext()) -
What does MoveNext return?
- The current item
- A bool: whether it advanced
- The total item count
- It throws
Show answer
A bool: whether it advanced — Correct. MoveNext returns a bool; true means it advanced, false means the sequence ended.
-
Match the member to its role
- MoveNext
- Whether it advanced
- Current
- Current value
- Reset
- Return to start
- Dispose
- Release resource