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.
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.
Syntax
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
Reference
Stack vs Queue, List, and ConcurrentStack
Pick the collection that matches how items should come out:
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);
}
}
}
Output
3
red
red
2
blue
white
How It Works
One type argument.Stack<string> means every item is a string. There are no keys and no positions, only a pile with a top.
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.
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.
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");
}
}
}
Output
Took 7
The pile is empty
How It Works
The risk.Pop() on an empty stack throws InvalidOperationException. A bare call is only safe when you already know something is on the pile.
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.
Way two: TryPop. It returns false for an empty stack instead of throwing, so the else branch prints The pile is empty.
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());
}
}
Output
Undo: deleted a word
Undo: made it bold
1
typed Hello
How It Works
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.
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.
What remains. Only the first edit is left, so Count prints 1. The history has been rolled back to just after typing.
Peek shows the next undo.Peek() reports typed Hello, the change that would be undone next, without removing it.
Continue
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.
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.