C# Stack

Beginner
7 min read
Updated: Nov 2026
3 examples
Stack

Definition and Usage

In C#, Stack<T> is a collection that works like a pile of plates. It is last in, first out (LIFO): the item you added most recently is the first one to come off. The same idea powers the Back button in a browser and the Undo command in an editor. You put an item on top with Push(), take the top item off with Pop(), and read the top without removing it with Peek().

The Count property tells you how many items are stacked. A stack allows duplicates and, for reference types, null. It has no indexer (you cannot write plates[0]). foreach, ToArray(), and CopyTo() all go from the top to the bottom: push 1, 2, 3 and a loop prints 3, 2, 1. The order is fixed, so printing is safe. It lives in System.Collections.Generic, so add using System.Collections.Generic; at the top of your file.

The Stack Methods index lists every method guide in this series.

Empty stack warning.

Pop() and Peek() throw InvalidOperationException when the stack is empty. Check Count first, or use TryPop and TryPeek in newer .NET. Also, Stack<T> is not thread-safe; use ConcurrentStack<T> when several threads share one stack.

C# Syntax

Common first steps:

C#
using System.Collections.Generic;

Stack<string> plates = new Stack<string>();
plates.Push("white");                  // put on top
plates.Push("blue");
string top = plates.Peek();            // "blue" (not removed)
string taken = plates.Pop();           // "blue" (removed)
int total = plates.Count;              // 1

// Start with items already stacked (the LAST array item ends up on top):
Stack<int> numbers = new Stack<int>(new int[] { 1, 2, 3 });   // top is 3

Stack vs Queue, List, and ConcurrentStack

Pick the collection that matches how items should come out:

TypeOrder of removalAccessGood for
Stack<T>Last in, first out (newest first)Push and pop at the top only, no indexerUndo history, going back, matching brackets, reversing
Queue<T>First in, first out (oldest first)Add at one end, take from the other, no indexerWaiting lines and jobs in arrival order (see Queue)
List<T>Any item, by indexRead, insert, and remove anywhereAn ordered list you change in many places (see List)
ConcurrentStack<T>Last in, first outThread-safe push and popA stack shared by several threads

Pop vs TryPop

Both take the top item. They differ when the stack might be empty:

CallStack has itemsStack is emptyAvailable in
Pop()Removes and returns the top itemThrows InvalidOperationExceptionAll .NET versions
TryPop(out x)Returns true, x is the top itemReturns false, x is the default valueNewer .NET (.NET Core 2.0+)
Peek()Returns the top item, keeps itThrows InvalidOperationExceptionAll .NET versions
TryPeek(out x)Returns true, x is the top itemReturns false, x is the default valueNewer .NET (.NET Core 2.0+)

C# Examples

Example 1 — Push, Peek, and Pop

A first program: three plates are stacked, you look at the top one, take it off, and loop over what is left. The loop goes from the top down.

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

class Program {
    static void Main() {
        Stack<string> plates = new Stack<string>();

        plates.Push("white");
        plates.Push("blue");
        plates.Push("red");
        Console.WriteLine(plates.Count);

        Console.WriteLine(plates.Peek());
        Console.WriteLine(plates.Pop());
        Console.WriteLine(plates.Count);

        foreach (string plate in plates) {
            Console.WriteLine(plate);
        }
    }
}

How It Works

  1. One type argument. Stack<string> means every item is a string. There are no keys and no positions, only a pile with a top.
  2. Stack them up. Each Push lands on top of the others. After three calls Count is 3, and red, the newest plate, is on top.
  3. Look, then take. Peek() shows red and leaves it there, then Pop() removes red and returns it. That is why red prints twice and Count drops to 2.
  4. Top to bottom. The foreach visits blue first and white last, the reverse of the order they were pushed. Looping does not remove anything.

Example 2 — Take From a Stack Without a Crash

Take the top item using a Count check, then ask again with TryPop when the stack is already empty.

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

class Program {
    static void Main() {
        Stack<int> pile = new Stack<int>();
        pile.Push(7);

        if (pile.Count > 0) {
            Console.WriteLine("Took " + pile.Pop());
        }

        if (pile.TryPop(out int top)) {
            Console.WriteLine("Took " + top);
        } else {
            Console.WriteLine("The pile is empty");
        }
    }
}

How It Works

  1. The risk. Pop() on an empty stack throws InvalidOperationException. A bare call is only safe when you already know something is on the pile.
  2. Way one: check Count. One number is stored, so pile.Count > 0 is true. The call runs and prints Took 7, and the pile ends up empty.
  3. Way two: TryPop. It returns false for an empty stack instead of throwing, so the else branch prints The pile is empty.
  4. Version note. TryPop is in newer .NET (.NET Core 2.0 and later). On classic .NET Framework, use the Count way.

Example 3 — Build a Tiny Undo History

A text editor remembers each change on a stack. Undo means “take the latest change off the top”, so the newest change is always undone first.

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

class Program {
    static void Main() {
        Stack<string> history = new Stack<string>();

        history.Push("typed Hello");
        history.Push("made it bold");
        history.Push("deleted a word");

        Console.WriteLine("Undo: " + history.Pop());
        Console.WriteLine("Undo: " + history.Pop());

        Console.WriteLine(history.Count);
        Console.WriteLine(history.Peek());
    }
}

How It Works

  1. Record every step. Three edits are pushed in the order they happened, so the deleted word is the most recent entry and sits on top.
  2. Undo takes the top. The first Pop() returns deleted a word, the last thing you did. The second one returns made it bold, and the same order works backwards through time.
  3. What remains. Only the first edit is left, so Count prints 1. The history has been rolled back to just after typing.
  4. Peek shows the next undo. Peek() reports typed Hello, the change that would be undone next, without removing it.

Next: C# Stack Methods Index

After you know what a Stack is for, open the method index for a full tutorial on each Stack API.

Start withWhy
Push()Put an item on top of the stack
Pop()Take the top item off, and handle an empty stack
Peek()Look at the top item without removing it
GetEnumerator()Loop over the stack from top to bottom

Full list: C# Stack Methods index (/c-sharp/stack/method).

Frequently Asked Questions

It is a collection in System.Collections.Generic that stores items in last in, first out (LIFO) order. Push puts an item on top, Pop removes and returns the top item, and Peek reads the top without removing it.
A Stack is last in, first out: the newest item leaves first. A Queue is first in, first out: the oldest item leaves first. Use a Stack for undo and going back, and a Queue for lines and jobs that run in arrival order.
It throws InvalidOperationException. Check Count > 0 first, or use TryPop (newer .NET), which returns false instead of throwing. Peek behaves the same way, and TryPeek is its safe version.
From the top to the bottom, so the newest item comes first. If you push 1, 2, 3, then foreach prints 3, 2, 1. ToArray and CopyTo use the same top-to-bottom order.
No. If several threads push and pop at the same time, use ConcurrentStack<T> from System.Collections.Concurrent. The older non-generic System.Collections.Stack also exists, but prefer Stack<T> because it is type-safe.

Browse every Stack method

Open the methods index for categorized guides with examples and FAQs.

Stack Methods Index →

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.

8 people found this page helpful