In C#, Dictionary.GetEnumerator() returns an enumerator: a small object that walks through the dictionary and gives you one KeyValuePair at a time. Each pair has a Key and a Value.
You rarely call it yourself. A foreach loop calls GetEnumerator() for you, then MoveNext() and Current until the end. The return type is Dictionary<TKey,TValue>.Enumerator, which is a struct.
This is an instance member of Dictionary<TKey,TValue> (System.Collections.Generic). Call it on a dictionary variable, such as ages.GetEnumerator(...). A dictionary is a class, so two variables can share one dictionary.
Syntax
Use foreach in normal code. Call GetEnumerator directly only when you need manual control.
C#
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25);
foreach (KeyValuePair<string, int> pair in ages) {
Console.WriteLine(pair.Key + " " + pair.Value);
}
Dictionary<string, int>.Enumerator e = ages.GetEnumerator();
while (e.MoveNext()) { /* use e.Current */ }
Call
What it does
foreach (var pair in ages)
The easy way. The compiler calls GetEnumerator(), MoveNext(), and Current for you.
ages.GetEnumerator()
Returns the struct enumerator so you can call MoveNext() yourself.
foreach (string k in ages.Keys)
Loop over only the keys.
The order of pairs is not guaranteed. A dictionary often returns pairs in the order they were added, but you must not rely on that, especially after removals.
Library declarations
C#
public Dictionary<TKey, TValue>.Enumerator GetEnumerator();
Parameters
Parameter
Description
None
GetEnumerator() takes no parameters.
Return Value
Return Value
Description
Dictionary<TKey,TValue>.Enumerator
A struct enumerator. Its Current is a KeyValuePair<TKey,TValue>. Call MoveNext() to step forward.
C# Examples
Example 1 — Total the Ages with foreach
Add up every value. The total is the same in any order.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25);
ages.Add("Ravi", 31);
ages.Add("Meena", 28);
int total = 0;
int pairs = 0;
foreach (KeyValuePair<string, int> pair in ages) {
total += pair.Value;
pairs++;
}
Console.WriteLine("Total age: " + total);
Console.WriteLine("Pairs: " + pairs);
}
}
Output
Total age: 84
Pairs: 3
How It Works
Hidden call.foreach asks the dictionary for its enumerator, so you never type GetEnumerator().
One pair per turn. Each pass gives a KeyValuePair; pair.Value is that person's age.
Order-proof output. 25 plus 31 plus 28 is 84 in any order.
Three turns. The loop ran once per pair, so pairs is 3.
Example 2 — Walk the Enumerator by Hand
Call GetEnumerator yourself and add up the letters in all keys.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25);
ages.Add("Ravi", 31);
ages.Add("Meena", 28);
int letters = 0;
int pairs = 0;
using (Dictionary<string, int>.Enumerator e = ages.GetEnumerator()) {
while (e.MoveNext()) {
KeyValuePair<string, int> pair = e.Current;
letters += pair.Key.Length;
pairs++;
}
}
Console.WriteLine("Pairs: " + pairs);
Console.WriteLine("Key letters: " + letters);
}
}
Output
Pairs: 3
Key letters: 13
How It Works
Struct enumerator.ages.GetEnumerator() returns a Dictionary<string, int>.Enumerator value that you keep in the variable e.
MoveNext first. The enumerator starts before the first pair; MoveNext() steps onto one and returns false at the end.
Current is the pair.e.Current gives a KeyValuePair, and pair.Key.Length counts the letters in each name.
Totals. Asha (4) plus Ravi (4) plus Meena (5) is 13 letters.
Example 3 — Why You Should Not Add Inside foreach
See the InvalidOperationException, then update values safely with a copy of the keys.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25);
ages.Add("Ravi", 31);
try {
foreach (KeyValuePair<string, int> pair in ages) {
ages.Add(pair.Key + "2", 0);
}
} catch (InvalidOperationException) {
Console.WriteLine("Cannot change while looping");
}
Console.WriteLine(ages.Count);
List<string> keys = new List<string>(ages.Keys);
foreach (string key in keys) {
ages[key] = ages[key] + 1;
}
Console.WriteLine(ages["Asha"]);
Console.WriteLine(ages["Ravi"]);
}
}
Output
Cannot change while looping
3
26
32
How It Works
First pass works. The loop reaches the first pair and adds one new key, so the dictionary now has 3 pairs.
Next step fails. The enumerator sees the change, so the next MoveNext() throws InvalidOperationException and the catch block prints a message.
One Add survived.Count is 3 because one Add finished before the error. Which key it was depends on enumeration order, so the code never prints it.
Safe pattern. Copy the keys into a List and update the dictionary inside that loop. Asha goes from 25 to 26 and Ravi from 31 to 32.
Frequently Asked Questions
It returns a Dictionary<TKey,TValue>.Enumerator struct. Its Current property is a KeyValuePair<TKey,TValue>, and MoveNext() steps to the next pair.
Almost never. A foreach loop calls it for you.
No. Pairs often come back in the order they were added, but that is not promised. Use SortedDictionary for sorted keys.
You added a key to the dictionary while a foreach was running. Loop over a copy of the keys, such as new List<string>(dict.Keys), and change the dictionary there.
Use foreach (string key in dict.Keys) or foreach (int value in dict.Values).