Using Stack<T>.TryPop in C#
Learn how Stack<T>.TryPop avoids exceptions on empty stacks in C#, when to use it instead of Pop, and how ConcurrentStack<T> handles thread safety.

The Exception Problem TryPop Removes
Stack<T>.Pop() throws InvalidOperationException when the stack is empty. That makes the method awkward in code paths where an empty stack is a normal condition rather than a programming error. Stack<T>.TryPop exists to handle that case without exception handling.
Stack<string> messages = new Stack<string>();
if (messages.TryPop(out string next))
{
Console.WriteLine($"Processing: {next}");
}
else
{
Console.WriteLine("No messages to process");
}The method returns true when an element was removed, and false when the stack was empty. The removed element is written to the out parameter.
Signature and Return Behavior
Stack<T>.TryPop has the signature public bool TryPop(out T result). When the stack is empty, it returns false and sets result to default(T). For reference types that is null; for value types it is the zero-initialized value.
Stack<int> empty = new Stack<int>();
bool removed = empty.TryPop(out int value);
Console.WriteLine(removed); // False
Console.WriteLine(value); // 0The out parameter must be assigned before the method returns, so the compiler guarantees that value is initialized regardless of the outcome. You never read an unassigned local variable after calling TryPop.
Choosing Between Pop and TryPop
The decision between these two methods comes down to whether an empty stack is an expected state or a bug in your program.
| Behavior | Pop | TryPop |
|---|---|---|
| Empty stack | Throws InvalidOperationException | Returns false |
| Removed element | Return value | Out parameter |
| Exception overhead | Yes when empty | None |
| Best fit | Empty indicates a logic error | Empty is a normal state |
Use Pop when an empty stack indicates a logic error that should surface loudly and fail fast. Use TryPop when the stack acts as a local buffer or work queue that may legitimately run dry during normal operation.
A Practical Worker Example
A common pattern is a stack of pending work items drained by a loop. TryPop removes the need for a separate Count check and removes exception handling from the loop body.
Stack<Action> pendingWork = new Stack<Action>();
pendingWork.Push(() => Console.WriteLine("Task A"));
pendingWork.Push(() => Console.WriteLine("Task B"));
while (pendingWork.TryPop(out Action task))
{
task();
}The loop terminates naturally when the stack is exhausted. No exception is thrown on the final iteration, and the code reads more clearly than an equivalent Count > 0 guard followed by Pop.
Thread Safety and ConcurrentStack<T>
Stack<T>.TryPop is not thread-safe. Concurrent calls from multiple threads can corrupt the internal array and produce incorrect results. If the stack is shared across threads, use ConcurrentStack<T>, which provides its own TryPop with the same calling shape.
ConcurrentStack<int> shared = new ConcurrentStack<int>();
shared.Push(1);
shared.Push(2);
if (shared.TryPop(out int item))
{
Console.WriteLine(item);
}ConcurrentStack<T>.TryPop also returns false when the collection is empty, so the calling pattern stays identical. The tradeoff is a small synchronization cost per operation, which is only worth paying when the stack is genuinely accessed from multiple threads.
Performance and Allocation Behavior
The main performance argument for TryPop is that it avoids exception construction. Throwing and catching an exception allocates an exception object and unwinds the stack, which is far more expensive than a simple branch. In a loop that frequently drains an empty stack, TryPop avoids that cost entirely.
There is no allocation in either outcome: a successful pop is a simple array access and write, and an empty-stack result just returns false. The out parameter does not box value types, so no hidden allocation is introduced for Stack<int> or similar value-type stacks.
Common Mistakes
A common mistake is forgetting to check the return value. TryPop does not throw, so an unchecked call silently discards the result:
// Misleading: the return value is ignored
stack.TryPop(out int item);
Console.WriteLine(item); // default(int) when emptyThe compiler does not warn about this, so the failure is silent. Always branch on the returned bool before using the out value.
Another mistake is assuming TryPop on Stack<T> is safe under concurrency. It is not; only ConcurrentStack<T> provides that guarantee. Mixing Push and TryPop from multiple threads on a plain Stack<T> can produce unpredictable ordering and lost elements.
Compatibility Notes
Stack<T>.TryPop was introduced in .NET Core 2.0 and is available in .NET 5 and later, as well as in .NET Framework 4.7.1 and later. If the target framework predates that, the equivalent pattern is a Count check followed by Pop:
if (stack.Count > 0)
{
T item = stack.Pop();
}That pattern is not atomic, so it is not safe under concurrency. On older frameworks, guard the operation with a lock if multiple threads touch the stack. On modern frameworks, TryPop removes the separate Count check, but Stack<T> remains non-thread-safe; use ConcurrentStack<T> if the stack is shared across threads.
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.