C# Stack GetEnumerator() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Stack

Definition

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

That means a loop sees the newest item first: push 1, 2, 3 and foreach prints 3, 2, 1. 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 is fixed. Looping does not remove the items.

This is an instance member of Stack<T> (System.Collections.Generic). Call it on a stack variable, such as history.GetEnumerator(...). A Stack<T> is a class, so two variables can share one stack. It is last in, first out (LIFO): the newest item sits on top and leaves first. It is not thread-safe; for several threads use ConcurrentStack<T>.

Syntax

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

C#
Stack<string> plates = new Stack<string>();
plates.Push("white");
plates.Push("blue");

foreach (string plate in plates) {         // calls GetEnumerator() for you
    Console.WriteLine(plate);              // blue, then white
}

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

The enumerator remembers a version number of the stack. If you call Push, Pop, 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.Stack has a similar method, but prefer Stack<T>.

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

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

Parameters

ParameterDescription
NoneGetEnumerator() takes no parameters.

Return Value

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

C# Examples

Example 1 — Visit Every Item Top to Bottom

Loop over a stack of numbers with foreach. The newest number comes first. After the loop the stack still holds every number.

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

class Program {
    static void Main() {
        Stack<int> numbers = new Stack<int>();
        numbers.Push(1);
        numbers.Push(2);
        numbers.Push(3);

        foreach (int n in numbers) {
            Console.WriteLine(n);
        }

        Console.WriteLine(numbers.Count);
    }
}

How It Works

  1. A hidden call. foreach asks the stack for an enumerator by calling GetEnumerator(), so you do not have to write it.
  2. The newest comes first. A stack always walks from the top down, so 3 prints before 2 and 1, the reverse of the push order. There is no random order here.
  3. Looking, not taking. The loop only reads each item; nothing is popped.
  4. Nothing was removed. Count still prints 3 after the loop, which shows that foreach only reads.

Example 2 — Walk the Stack With MoveNext and Current

Call GetEnumerator yourself and use MoveNext to go step by step. Print the first item, add up the numbers, and count the steps.

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

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

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

        while (e.MoveNext()) {
            if (steps == 0) {
                Console.WriteLine("First: " + e.Current);
            }
            sum += e.Current;
            steps++;
        }

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

How It Works

  1. Array to stack. The constructor pushes 5, then 10, then 15, so 15 is on top and 5 is at the bottom.
  2. Before the first item. A new enumerator is not on any item yet. The first MoveNext() moves it onto the top item and returns true, and Current is 15.
  3. Totals. The loop body runs three times, for 15, 10, and 5, so steps is 3 and sum is 30.
  4. Past the end. After the bottom item, MoveNext() returns false, and calling it once more still gives False.

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

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

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

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

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

        foreach (int n in stack.ToArray()) {
            stack.Pop();
        }
        Console.WriteLine(stack.Count);
    }
}

How It Works

  1. The first step works. The loop prints 3, the top item. Then Push(99) changes the stack while the enumerator is still active.
  2. A version check. Before the second step, the enumerator sees the stack changed and throws InvalidOperationException. Only the type name is printed, since messages vary.
  3. The change stays. The exception does not undo the Push. The stack holds 1, 2, 3, and 99, so Count prints 4.
  4. The safe pattern. stack.ToArray() makes a separate array, so the second loop can Pop() freely. Four items, four pops, and the last Count is 0.

Frequently Asked Questions

It returns an enumerator that visits the stack's items one by one from the top to the bottom. The foreach statement uses it automatically.
From the top to the bottom: the order of Pop. The newest item is visited first. If you push 1, 2, 3, foreach prints 3, 2, 1. This order is fixed, not random.
No. foreach only reads the items. To remove items as you go, use a while loop with Pop or TryPop.
Because the stack was changed (Push, Pop, Clear, and so on) after the loop started. Loop over stack.ToArray() or use a while loop if you need to change the stack.
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 on top of the stack without removing it; throws if the stack 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.

11 people found this page helpful