C# Stack TryPop() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Stack

Definition

In C#, Stack.TryPop(out result) is the safe version of Pop(). If an item is on the stack, it removes the top item, hands it to you in the out variable, and returns true. If the stack is empty, it returns false and does not throw.

Think of reaching for the top plate in a cupboard that might be bare. Instead of knocking over the shelf, you just learn "no plate". This helps in loops and in code where an empty stack is normal, such as checking brackets, where a closing bracket with nothing to match is a mistake you want to report, not a crash.

This is an instance member of Stack<T> (System.Collections.Generic). Call it on a stack variable, such as history.TryPop(...). A Stack<T> is a class, so two variables can share one stack. It is last in, first out (LIFO): the newest item sits on top and leaves first. It is not thread-safe; for several threads use ConcurrentStack<T>. TryPop exists in newer .NET versions (.NET Core 2.0 and later, and .NET Standard 2.1). It is not in classic .NET Framework, so check your project version.

Syntax

Pass an out variable. Read the bool result first, and only then use the variable.

C#
Stack<string> plates = new Stack<string>();
plates.Push("white");

if (plates.TryPop(out string top)) {
    // top is "white" here
}
bool again = plates.TryPop(out string none);   // false; none is null
CallWhat it does
plates.TryPop(out string top)If the stack has items: removes the top, stores it in top, returns true.
plates.TryPop(out string top) (empty)Returns false. top gets the default value (null for strings, 0 for int).
while (plates.TryPop(out var x)) { ... }A neat loop that unstacks everything and stops by itself when the stack is empty.
plates.TryPeek(out string top)The look-only version: no removal. See TryPeek().

Use the bool result to decide, not the value. A stack of int may hold a real 0, and an empty stack also gives 0, so only true / false tells them apart. Like Pop, it is O(1). In a multi-threaded program use ConcurrentStack<T>.TryPop, because a plain Stack<T> is not thread-safe.

Library declarations
C#
public bool TryPop(out T result);

Parameters

ParameterDescription
resultAn out parameter. When the method returns true, it holds the removed top item. When it returns false, it holds the default value of T.

Return Value

Return ValueDescription
booltrue if an item was removed from the top. false if the stack was empty (nothing changed).

C# Examples

Example 1 — Pop Safely and Read the Result

Pop the only name, then try again on the now-empty stack. Compare the bool and the out value each time.

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

class Program {
    static void Main() {
        Stack<string> names = new Stack<string>();
        names.Push("Asha");

        bool ok = names.TryPop(out string name);
        Console.WriteLine(ok);
        Console.WriteLine(name);

        ok = names.TryPop(out name);
        Console.WriteLine(ok);
        Console.WriteLine(name == null);
    }
}

How It Works

  1. The first try works. One name is on the stack, so it is removed, name becomes "Asha", and the method returns True.
  2. Declared inline. out string name creates the variable inside the call, so no separate declaration line is needed.
  3. The second try fails quietly. The stack is empty now, so the method returns False instead of throwing.
  4. A default is left behind. On failure name is reset to the default for string, which is null, so name == null prints True.

Example 2 — A Loop That Stops by Itself

Use TryPop as the loop condition. The numbers come off newest first, and no Count check is needed.

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

class Program {
    static void Main() {
        Stack<int> numbers = new Stack<int>();
        numbers.Push(4);
        numbers.Push(8);
        numbers.Push(15);

        int total = 0;
        while (numbers.TryPop(out int n)) {
            Console.WriteLine("Got " + n);
            total += n;
        }

        Console.WriteLine(total);
        Console.WriteLine(numbers.Count);
    }
}

How It Works

  1. The call is the condition. Every time the while line runs, it tries to take one item and tests whether that worked.
  2. Newest first. 15 was pushed last, so it is the first value in n. The order is 15, 8, 4, the reverse of the pushes.
  3. A natural end. After 4 is taken, the next try finds nothing and returns false, so the loop finishes without extra code.
  4. The totals. 15 + 8 + 4 is 27, and the stack ends empty with Count 0.

Example 3 — Check That Brackets Match

Push each opening bracket. When a closing bracket appears, pop one. If there is nothing to pop, the text is not balanced.

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

class Program {
    static bool IsBalanced(string text) {
        Stack<char> open = new Stack<char>();

        foreach (char c in text) {
            if (c == '(') {
                open.Push(c);
            } else if (c == ')') {
                if (!open.TryPop(out char _)) {
                    return false;
                }
            }
        }

        return open.Count == 0;
    }

    static void Main() {
        Console.WriteLine(IsBalanced("(a(b))c"));
        Console.WriteLine(IsBalanced("(()"));
        Console.WriteLine(IsBalanced("())("));
    }
}

How It Works

  1. Opening brackets wait. Each ( is pushed. The stack records how many are still unmatched, and the latest one is on top.
  2. Closing brackets pair up. Each ) tries to pop one waiting bracket. A successful TryPop means a match was found.
  3. No exception needed. In "())(" the second ) arrives when the stack is empty. TryPop returns false, so the method answers False right there.
  4. Leftovers count too. In "(()" every ) finds a partner, but one ( stays on the stack, so open.Count == 0 is false. Only the first text ends empty and gives True.

Frequently Asked Questions

It tries to remove the top item. If the stack has an item, it returns true and gives the item in the out parameter. If the stack is empty, it returns false and does not throw.
Pop throws InvalidOperationException on an empty stack. TryPop returns false instead. Use TryPop when an empty stack is a normal situation.
It has the default value of the item type, such as null for string or 0 for int. Do not treat it as real data.
It is in newer .NET versions: .NET Core 2.0 and later and .NET Standard 2.1. It is not in classic .NET Framework. If your project does not compile with it, use Count with Pop.
No. Stack<T> is not thread-safe. For several threads, use ConcurrentStack<T>, which has its own TryPop that is safe to call at the same time.

Back to the method index

See all 12 Stack method guides grouped by what they do.

Method 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.

9 people found this page helpful