C# Dictionary GetEnumerator() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Dictionary

Definition

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 */ }
CallWhat 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

ParameterDescription
NoneGetEnumerator() takes no parameters.

Return Value

Return ValueDescription
Dictionary<TKey,TValue>.EnumeratorA 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);
    }
}

How It Works

  1. Hidden call. foreach asks the dictionary for its enumerator, so you never type GetEnumerator().
  2. One pair per turn. Each pass gives a KeyValuePair; pair.Value is that person's age.
  3. Order-proof output. 25 plus 31 plus 28 is 84 in any order.
  4. 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);
    }
}

How It Works

  1. Struct enumerator. ages.GetEnumerator() returns a Dictionary<string, int>.Enumerator value that you keep in the variable e.
  2. MoveNext first. The enumerator starts before the first pair; MoveNext() steps onto one and returns false at the end.
  3. Current is the pair. e.Current gives a KeyValuePair, and pair.Key.Length counts the letters in each name.
  4. 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"]);
    }
}

How It Works

  1. First pass works. The loop reaches the first pair and adds one new key, so the dictionary now has 3 pairs.
  2. Next step fails. The enumerator sees the change, so the next MoveNext() throws InvalidOperationException and the catch block prints a message.
  3. 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.
  4. 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).

Next: Remove()

Remove a key and its value; returns true if it was found, false if not.

Remove() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful