C# Stack
last modified October 5, 2026
This article introduces the generic Stack<T> collection in C#. A stack follows last-in, first-out (LIFO) order: the newest item is the first one removed.
Stack<T> is in System.Collections.Generic. Its main operations work at the top of the collection, making it useful for undo histories, parsing, and depth-first processing.
C# Stack example
Use Push to put a value on top of the stack. Enumeration starts at the top, so the values appear in reverse order from their insertion.
using System.Collections.Generic;
var pages = new Stack<string>();
pages.Push("home");
pages.Push("products");
pages.Push("details");
foreach (var page in pages)
{
Console.WriteLine(page);
}
$ dotnet run details products home
Peeking and popping
Peek reads the top value without removing it. Pop returns and removes the top value. The non-try methods throw InvalidOperationException if the stack is empty.
var values = new Stack<int>();
values.Push(4);
values.Push(8);
values.Push(12);
Console.WriteLine($"Top: {values.Peek()}");
Console.WriteLine($"Removed: {values.Pop()}");
Console.WriteLine($"Count: {values.Count}");
$ dotnet run Top: 12 Removed: 12 Count: 2
Use TryPeek or TryPop when an empty stack is possible. They report whether an item was available instead of throwing.
var undo = new Stack<string>();
undo.Push("rename file");
if (undo.TryPop(out string? action))
{
Console.WriteLine($"Undo {action}");
}
if (!undo.TryPop(out _))
{
Console.WriteLine("No more actions");
}
$ dotnet run Undo rename file No more actions
Initializing and clearing a stack
A stack can be initialized from a sequence. The first sequence element becomes the bottom item, and the final element becomes the top item. Clear removes all items.
var numbers = new Stack<int>(new[] { 1, 2, 3 });
Console.WriteLine(numbers.Pop());
numbers.Clear();
Console.WriteLine(numbers.Count);
$ dotnet run 3 0
When to use a stack
A stack fits tasks where the most recent item should be handled first, such as traversing a tree depth-first or keeping a sequence of undo operations. Use Queue<T> instead when items must be processed in arrival order. Stack operations at the top are typically constant time.
Source
This article introduced the LIFO stack collection in C#.
Author
List all C# tutorials.