Returns an enumerator that can walk through the items.
IEnumerator<T>.Current
The item the enumerator is pointing at right now.
IEnumerator<T>.MoveNext()
Moves to the next item. Returns false when there are no more.
IEnumerator<T>.Reset()
Moves back to the start. Rarely used.
C# Examples
Example 1 — foreach over Different Types
The same loop works for a list and a string.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var fruits = new List<string> { "apple", "pear" };
foreach (string f in fruits) {
Console.WriteLine(f);
}
foreach (char c in "Hi") {
Console.WriteLine(c);
}
}
}
Output
apple
pear
H
i
How It Works
List is IEnumerable.foreach visits each item in order.
String is IEnumerable<char>. The second loop visits each character.
One loop style. You do not need to know how each collection stores data.
Example 2 — Walk Items by Hand
Do what foreach does yourself with GetEnumerator().
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var numbers = new List<int> { 10, 20, 30 };
IEnumerator<int> e = numbers.GetEnumerator();
while (e.MoveNext()) {
Console.WriteLine(e.Current);
}
}
}
Output
10
20
30
How It Works
Get the enumerator. It starts before the first number.
MoveNext() steps forward. It returns true while an item exists.
Current reads the item. The loop ends when MoveNext() returns false.
Example 3 — Create Your Own Sequence
A method that returns IEnumerable<int> can hand out values one at a time with yield return.
C#
using System;
using System.Collections.Generic;
class Program {
static IEnumerable<int> CountTo(int n) {
for (int i = 1; i <= n; i++) {
yield return i;
}
}
static void Main() {
foreach (int number in CountTo(3)) {
Console.WriteLine(number);
}
}
}
Output
1
2
3
How It Works
Return type.IEnumerable<int> says the method produces a sequence of numbers.
yield return. Hands back one value, then pauses until the loop asks for the next.
No list needed. The numbers are produced on demand.
Frequently Asked Questions
It is an interface for any sequence that can be looped over, such as arrays, lists, and strings.
foreach calls GetEnumerator(), then repeatedly calls MoveNext() and reads Current.
IEnumerable is the sequence. IEnumerator is the cursor that walks through it.
It lets a method return items one by one, pausing between each, without building a full list first.
No. Adding or removing items during foreach throws an InvalidOperationException.