In C#, GetEnumerator() returns a CharEnumerator that walks each character in the string one by one.
You call it with no parameters. Prefer foreach for daily code. If you use the enumerator directly, call MoveNext before reading Current.
Syntax
Call GetEnumerator on the string, or use foreach.
C#
CharEnumerator e = text.GetEnumerator();
Call
What it does
text.GetEnumerator()
Returns an enumerator that walks each character.
Most code should use foreach (char c in text) instead of calling GetEnumerator by hand.
Library declarations
C#
public CharEnumerator GetEnumerator();
Parameters
This method has no parameters.
Return Value
Return Value
Description
CharEnumerator
An enumerator for the characters in the string.
C# Examples
Example 1 — Manual MoveNext / Current
Call GetEnumerator() and print each character with an explicit while loop.
C#
using System;
class Program {
static void Main() {
string text = "C#";
using (CharEnumerator e = text.GetEnumerator()) {
while (e.MoveNext()) {
Console.WriteLine(e.Current);
}
}
}
}
Output
C
#
How It Works
Get an enumerator.GetEnumerator() starts before the first character.
Advance with MoveNext. First call lands on 'C'; second on '#'.
Read Current. Only after MoveNext() returns true.
using disposes.CharEnumerator implements IDisposable—using cleans up when done.
Example 2 — Prefer foreach
The same walk with foreach—clearer for everyday code, same underlying idea.
C#
using System;
class Program {
static void Main() {
string text = "Fun";
foreach (char c in text) {
Console.Write(c + " ");
}
Console.WriteLine();
}
}
Output
F u n
How It Works
foreach calls GetEnumerator. The compiler generates the MoveNext/Current loop.
Each iteration is one char.c becomes 'F', then 'u', then 'n'.
Less boilerplate. No manual using or while condition to write.
Use explicit GetEnumerator when teaching enumeration or controlling the loop yourself.
Example 3 — Count Letters with an Enumerator
Walk the string and count alphabetic characters—useful enumerator practice without needing indexes.
C#
using System;
class Program {
static void Main() {
string text = "C# 12";
int letters = 0;
using (CharEnumerator e = text.GetEnumerator()) {
while (e.MoveNext()) {
if (char.IsLetter(e.Current)) {
letters++;
}
}
}
Console.WriteLine($"Letters: {letters}");
}
}
Output
Letters: 1
How It Works
Walk every character."C# 12" yields C, #, space, 1, 2.
Test with char.IsLetter. Only 'C' counts as a letter.
Increment the counter. Final count is 1.
Need positions? Switch to a for loop with text[i] instead of an enumerator.
Frequently Asked Questions
GetEnumerator() returns a CharEnumerator that walks each character in the string.
No. Call it on the string with empty parentheses.
A CharEnumerator for the characters.
Usually no. Prefer foreach (char c in text).
The enumerator has no characters. MoveNext returns false immediately.