Using the C# Generic Stack<T> Effectively
Use C# generic Stack<T> for LIFO operations: construct and initialize a stack, use Push/Pop/Peek, iterate safely, understand performance, and avoid common mistakes.

When you need last-in-first-out behavior in C#, the generic Stack<T> class is the standard choice. Unlike the non-generic Stack, Stack<T> preserves type information and avoids boxing when the element type is a value type. This article covers initialization, core operations, iteration, performance, and common edge cases.
Understanding Stack<T> and Its LIFO Semantics
Stack<T> is a generic collection that implements IEnumerable<T> and follows a strict LIFO (last-in, first-out) order. The most recently added item is always the first one removed. This behavior is useful for undo histories, expression evaluation, backtracking algorithms, and parsing nested structures.
Because the element type is declared explicitly, you get compile-time type safety and avoid the casting overhead associated with the non-generic Stack. For example, a Stack<int> stores actual int values, not object references.
Declaring and Initializing a Generic Stack
You can create a Stack<T> with the parameterless constructor, specify an initial capacity when you know the approximate number of elements, or populate it from an IEnumerable<T>.
// Empty stack with default capacity
Stack<string> messages = new Stack<string>();
// Stack with an initial capacity
Stack<int> numbers = new Stack<int>(32);
// Stack initialized from a collection
var fruits = new List<string> { "apple", "banana", "cherry" };
Stack<string> fruitStack = new Stack<string>(fruits);The constructor that accepts an IEnumerable<T> copies the elements in source order, but the last element becomes the top of the stack. In the example above, fruitStack.Peek() returns "cherry". This is a common source of confusion when building a stack from an existing collection.
Core Operations: Push, Pop, and Peek
The three fundamental operations are Push, Pop, and Peek. Push adds an item to the top, Pop removes and returns the top item, and Peek returns the top item without removing it.
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
int top = stack.Peek(); // 30, stack still contains 30
int removed = stack.Pop(); // 30, now stack contains 10 and 20Pop and Peek throw an InvalidOperationException if the stack is empty. To avoid exception handling in normal control flow, check Count first or use TryPop and TryPeek, which return a bool and an out parameter.
if (stack.TryPop(out int value))
{
Console.WriteLine(value);
}
else
{
Console.WriteLine("Stack was empty");
}TryPop and TryPeek are convenient when a stack may legitimately be empty at the time of the call. They do not make Stack<T> thread-safe: if one thread can modify the stack while another calls TryPop, you need a lock or ConcurrentStack<T>.
Checking the Number of Elements: Count
Count returns the number of items currently in the stack. It is an O(1) operation because the stack maintains an internal size counter. Checking Count is clearer than using Peek in a try-catch block.
if (stack.Count > 0)
{
// Safe to call Pop or Peek
}Pop removes the top element from the logical collection and returns it. The backing array may still have unused capacity after many pops. If you are storing many large objects and do not expect the stack to grow again, TrimExcess can shrink the backing array. In most cases this is unnecessary and can be counterproductive if growth resumes.
Iterating Over a Stack Without Removing Items
Stack<T> implements IEnumerable<T>, and its enumerator iterates from the top of the stack to the bottom. A foreach loop therefore visits elements in LIFO order without modifying the stack.
Stack<string> stack = new Stack<string>();
stack.Push("first");
stack.Push("second");
stack.Push("third");
foreach (string item in stack)
{
Console.WriteLine(item); // third, second, first
}This behavior is intentional and documented. If you need FIFO order, use Queue<T> instead. Reversing the iteration order by calling ToArray() and iterating backward is usually a sign that Stack<T> is the wrong collection type.
Common Mistakes and Edge Cases
A frequent mistake is assuming that the IEnumerable<T> constructor preserves the source order when the stack is read. As shown earlier, the last element of the source becomes the top of the stack. Another common mistake is calling Pop or Peek without checking Count, which throws in production code.
A more subtle issue involves value types. Stack<T> stores value types directly without boxing when the type argument itself is a value type. If you declare a Stack<object> and push value types, boxing still occurs.
Capacity growth is another consideration. Stack<T> uses an internal array, and when the array is full, it replaces it with a larger one and copies the existing elements. That copy is O(n), but it happens rarely enough that Push remains O(1) amortized. If you know the approximate maximum size in advance, pass it to the constructor to reduce avoidable resizing.
Performance and Memory Characteristics
Push is O(1) amortized. Pop, Peek, and Count are O(1). Contains is O(n) because it performs a linear scan.
Memory-wise, Stack<T> uses an array that can be larger than the element count. Unused slots are not a problem for small stacks. For a large stack after many pops, TrimExcess can reduce the backing array to match the current count, but it reallocates memory and should be used only when the stack is not expected to grow again soon.
Compared with a List<T> used as a stack through Add and RemoveAt(list.Count - 1), Stack<T> is more explicit and prevents accidental index misuse. The performance characteristics are similar, but Stack<T> provides a clearer contract and dedicated methods.
Choosing Between Stack<T> and Other Collections
If you need LIFO semantics, Stack<T> is the right choice. If you need FIFO, use Queue<T>. If you need random access by index, use List<T> or an array. If you need to add and remove at both ends, consider LinkedList<T> or a custom deque.
The choice is not only about performance. Stack<T> communicates intent. When another developer reads stack.Push(item) and stack.Pop(), the order of operations is immediately clear. A List<T> with manual index management is more error-prone and obscures algorithm logic.
For concurrent scenarios, .NET provides ConcurrentStack<T> in the System.Collections.Concurrent namespace. It is designed for safe concurrent access. If multiple threads share a stack, use ConcurrentStack<T> instead of adding ad hoc locking around Stack<T>.
Using Stack<T> in Recursive Algorithms
A common use of Stack<T> is replacing recursion with an explicit stack, especially when you want to avoid deep call stacks. For example, a depth-first traversal of a tree can be written iteratively:
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.Push(root);
while (stack.Count > 0)
{
TreeNode node = stack.Pop();
Console.WriteLine(node.Value);
// Push children in reverse order to preserve original order
for (int i = node.Children.Count - 1; i >= 0; i--)
{
stack.Push(node.Children[i]);
}
}This pattern avoids recursion depth limits and can be easier to reason about in certain algorithms. The generic type ensures that node is a TreeNode, so no cast is required.
Final Code Example: Balanced Parentheses Checker
A classic use of a stack is checking balanced parentheses. The following method uses Stack<char> to validate that every opening bracket has a matching closing bracket in the correct order.
public static bool AreBalanced(string input)
{
Stack<char> stack = new Stack<char>();
foreach (char c in input)
{
if (c == '(' || c == '[' || c == '{')
{
stack.Push(c);
}
else if (c == ')' || c == ']' || c == '}')
{
if (stack.Count == 0)
return false;
char open = stack.Pop();
if ((c == ')' && open != '(') ||
(c == ']' && open != '[') ||
(c == '}' && open != '{'))
{
return false;
}
}
}
return stack.Count == 0;
}The method returns false if a closing bracket appears without a matching opening bracket or if the bracket types do not match. At the end, the stack must be empty for the input to be balanced. This example shows how Stack<T>'s type safety and LIFO behavior directly support a clean implementation.
Understanding the behavior, performance, and appropriate use of the generic stack will help you write clearer code when your algorithm requires LIFO order. Whether you are implementing an undo system, a parser, or a graph traversal, Stack<T> is a fundamental tool that fits naturally into your codebase.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.