C# Stack Example: Last-In, First-Out Collections

A stack hands items back in the reverse order you added them: last in, first out (LIFO). Think of a pile of plates. You use one whenever the most recent item is the one you need next, as in undo history, expression parsing, or walking a tree without recursion.

In current .NET, use the generic Stack<T> from System.Collections.Generic. The non-generic System.Collections.Stack stores object and is only worth knowing about for legacy code (see the end of the post).

Push, pop and peek

var stack = new Stack<string>();
stack.Push("Obj1");
stack.Push("Obj2");
stack.Push("Obj3");

foreach (string item in stack)
{
    Console.WriteLine(item);
}

string top = stack.Pop();
Console.WriteLine($"Popped: {top}");
Console.WriteLine($"Count: {stack.Count}");
Console.WriteLine($"Contains Obj1: {stack.Contains("Obj1")}");

Output:

Obj3
Obj2
Obj1
Popped: Obj3
Count: 2
Contains Obj1: True

Push adds an item to the top. Pop removes the top item and returns it. Peek returns the top item without removing it. All three are O(1); Push is O(n) only on the occasional call that has to grow the internal array.

Notice the foreach loop: it walks the stack from top to bottom, the same order Pop would return the items, and it does not remove anything. ToArray() uses the same order.

Empty stacks throw

Calling Pop or Peek on an empty stack throws InvalidOperationException. Either check Count first or use TryPop and TryPeek (available since .NET Core 2.0), which return false instead of throwing:

while (stack.TryPop(out string? item))
{
    Console.WriteLine($"Processing {item}");
}

That loop also shows the usual way to drain a stack.

A practical example: balanced brackets

Checking whether brackets in a string are properly nested is the classic stack problem. Every opening bracket is pushed; every closing bracket must match the one on top.

Console.WriteLine(IsBalanced("{ a[1] + (b * c) }"));  // True
Console.WriteLine(IsBalanced("(a[1)]"));              // False
Console.WriteLine(IsBalanced("((x)"));                // False

static bool IsBalanced(string text)
{
    var open = new Stack<char>();

    foreach (char c in text)
    {
        switch (c)
        {
            case '(' or '[' or '{':
                open.Push(c);
                break;

            case ')' or ']' or '}':
                if (!open.TryPop(out char last) || last != OpeningFor(c))
                    return false;
                break;
        }
    }

    // Anything left over was opened and never closed.
    return open.Count == 0;
}

static char OpeningFor(char closing) => closing switch
{
    ')' => '(',
    ']' => '[',
    _ => '{'
};

The same pattern, push on the way in and pop on the way out, is how you turn a recursive tree walk into a loop. That is worth doing when the tree can be deep enough to overflow the call stack.

Things to keep in mind

Building a stack from a collection. new Stack<int>([1, 2, 3]) pushes the items in order, so 3 ends up on top and is popped first. People often expect the opposite.

Memory. A stack never shrinks its internal array on its own. If one briefly held a million items and now holds ten, call TrimExcess().

Thread safety. Stack<T> is not safe for concurrent writes. If several threads push and pop, use ConcurrentStack<T> from System.Collections.Concurrent, which offers the same TryPop and TryPeek methods without any locking on your side.

The legacy non-generic Stack

Older code uses System.Collections.Stack:

using System.Collections;

Stack stack = new Stack();
stack.Push("Obj1");
object popped = stack.Pop();
string text = (string)popped;

It behaves the same way, but every item is an object: value types are boxed on the way in, and you need a cast on the way out that fails only at run time if the type is wrong. Replacing it with Stack<T> is usually a mechanical change.

Related examples

Leave a Comment