C# Queue GetEnumerator() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Queue

Definition

In C#, Queue.GetEnumerator() returns an enumerator: a small helper object that visits each item of a Queue<T> one by one, from the front to the back. The type is Queue<T>.Enumerator, a struct.

Most of the time you never call it yourself. A foreach loop calls GetEnumerator() for you, then calls MoveNext() and reads Current on every step. Unlike a HashSet, the order of a queue is fixed and predictable, so printing in a loop is safe. Looping does not remove the items.

This is an instance member of Queue<T> (System.Collections.Generic). Call it on a queue variable, such as line.GetEnumerator(...). A Queue<T> is a class, so two variables can share one queue. It is first in, first out (FIFO): items leave in the order they arrived. It is not thread-safe; for several threads use ConcurrentQueue<T>.

Syntax

Use foreach in normal code. Call GetEnumerator by hand only when you need step-by-step control.

C#
Queue<string> line = new Queue<string>();
line.Enqueue("Asha");
line.Enqueue("Ben");

foreach (string name in line) {           // calls GetEnumerator() for you
    Console.WriteLine(name);              // Asha, then Ben
}

Queue<string>.Enumerator e = line.GetEnumerator();
while (e.MoveNext()) {
    Console.WriteLine(e.Current);         // the same walk, written by hand
}
CallWhat it does
foreach (var x in queue)The normal way. Visits items front to back and leaves the queue unchanged.
var e = queue.GetEnumerator();Gets the Queue<T>.Enumerator struct. Then call MoveNext() and read Current.
queue.Enqueue(5) inside the loopChanging the queue while looping makes the next step throw InvalidOperationException.
foreach (var x in queue.ToArray())Loop over a copy so you can change the queue safely. See ToArray().

The enumerator remembers a version number of the queue. If you call Enqueue, Dequeue, Clear, or TrimExcess after the loop started, the next MoveNext() throws InvalidOperationException. Because the enumerator is a struct, do not copy it into another variable halfway through; keep using the one variable. The non-generic System.Collections.Queue has a similar method, but prefer Queue<T>.

Library declarations
C#
public Queue<T>.Enumerator GetEnumerator();

// Also available through the interfaces:
IEnumerator<T> IEnumerable<T>.GetEnumerator();

Parameters

ParameterDescription
NoneGetEnumerator() takes no parameters.

Return Value

Return ValueDescription
Queue<T>.EnumeratorAn enumerator positioned before the first item. Call MoveNext() once to reach the front item, then read Current.

C# Examples

Example 1 — Visit Every Item Front to Back

Loop over a queue of names with foreach. The order is the order they joined. After the loop the queue still holds every name.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        Queue<string> line = new Queue<string>();
        line.Enqueue("Asha");
        line.Enqueue("Ben");
        line.Enqueue("Chitra");

        foreach (string name in line) {
            Console.WriteLine(name);
        }

        Console.WriteLine(line.Count);
    }
}

How It Works

  1. Hidden call. foreach asks the queue for an enumerator by calling GetEnumerator(), so you do not have to write it.
  2. Fixed order. A queue always walks from the front to the back, so the names print in the order they were enqueued. There is no random order here.
  3. Looking, not taking. The loop only reads each item; nobody is removed.
  4. Count proves it. After the loop, Count still prints 3.

Example 2 — Walk the Queue With MoveNext and Current

Call GetEnumerator yourself and use MoveNext to go step by step, adding up numbers and counting steps.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        Queue<int> numbers = new Queue<int>(new int[] { 5, 10, 15 });

        Queue<int>.Enumerator e = numbers.GetEnumerator();
        int sum = 0;
        int steps = 0;

        while (e.MoveNext()) {
            sum += e.Current;
            steps++;
        }

        Console.WriteLine(steps);
        Console.WriteLine(sum);
        Console.WriteLine(e.MoveNext());
    }
}

How It Works

  1. Before the first item. A new enumerator is not on any item yet. The first MoveNext() moves it onto the front item (5) and returns true.
  2. Current reads the item. Inside the loop, e.Current is the item the enumerator is standing on, and the code adds it to sum.
  3. Totals. The loop body runs three times, for 5, 10, and 15, so steps is 3 and sum is 30.
  4. Past the end. After the last item, MoveNext() returns false, and calling it once more still gives False.

Example 3 — What Happens If You Change the Queue in a foreach

Enqueue a number from inside a foreach. The next step fails. Then use ToArray to loop safely.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        Queue<int> queue = new Queue<int>(new int[] { 1, 2, 3 });

        try {
            foreach (int n in queue) {
                Console.WriteLine(n);
                queue.Enqueue(99);
            }
        } catch (InvalidOperationException ex) {
            Console.WriteLine(ex.GetType().Name);
        }
        Console.WriteLine(queue.Count);

        foreach (int n in queue.ToArray()) {
            queue.Dequeue();
        }
        Console.WriteLine(queue.Count);
    }
}

How It Works

  1. First step works. The loop prints 1. Then Enqueue(99) changes the queue while the enumerator is still active.
  2. Version check. Before the second step, the enumerator notices the queue changed and throws InvalidOperationException. Only the type name is printed, since messages vary.
  3. The change stayed. The exception does not undo the Enqueue. The queue holds 1, 2, 3, and 99, so Count prints 4.
  4. Safe pattern. queue.ToArray() makes a separate array, so the second loop can Dequeue() freely. Four items, four dequeues, and the last Count is 0.

Frequently Asked Questions

It returns an enumerator that visits the queue's items one by one from the front to the back. The foreach statement uses it automatically.
From the front to the back: the order of Dequeue. The first item you would dequeue is the first one the loop visits. This order is fixed, not random.
No. foreach only reads the items. To remove items as you go, use a while loop with Dequeue or TryDequeue.
Because the queue was changed (Enqueue, Dequeue, Clear, and so on) after the loop started. Loop over queue.ToArray() or use a while loop if you need to change the queue.
A struct. This avoids a memory allocation in foreach, but it also means you should not copy it into other variables while you are using it.

Next: Peek()

Read the item at the front of the queue without removing it; throws if the queue is empty.

Peek() 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.

13 people found this page helpful