In C#, Stack.TryPeek(out result) is the safe version of Peek(). If the stack has an item, it copies the top item into the out variable and returns true. If the stack is empty, it returns false and does not throw. In both cases the stack is left unchanged.
It is a quick question to yourself: "Is there a plate up there, and what color?" You get a yes with the color, or a no. Nothing is lifted. To also take the item off, use TryPop().
This is an instance member of Stack<T> (System.Collections.Generic). Call it on a stack variable, such as history.TryPeek(...). 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>. TryPeek 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 first, then use the value only when it is true.
C#
Stack<string> plates = new Stack<string>();
plates.Push("white");
if (plates.TryPeek(out string top)) {
// top is "white"; it is still on the stack
}
bool has = new Stack<string>().TryPeek(out string none); // false
Call
What it does
plates.TryPeek(out string top)
If the stack has items: stores the top item in top and returns true. Nothing is removed.
plates.TryPeek(out string top) (empty)
Returns false. top gets the default value (null for strings, 0 for int).
plates.TryPeek(out _)
Use a discard when you only care whether the stack has an item, not what it is.
Decide with the bool, not with the out value. A stack of int may hold a real 0, and an empty stack also gives 0. TryPeek is O(1). Classic .NET Framework does not have it; there you can write stack.Count > 0 ? stack.Peek() : default by hand.
Library declarations
C#
public bool TryPeek(out T result);
Parameters
Parameter
Description
result
An out parameter. When the method returns true, it holds the top item. When it returns false, it holds the default value of T.
Return Value
Return Value
Description
bool
true if the stack has at least one item and the top item was copied to result. false if the stack is empty.
C# Examples
Example 1 — Peek Without Throwing
Peek at a one-item stack, then at an empty stack, and compare the bool results and the Count.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<string> plates = new Stack<string>();
plates.Push("red");
bool found = plates.TryPeek(out string top);
Console.WriteLine(found);
Console.WriteLine(top);
Console.WriteLine(plates.Count);
Stack<string> bare = new Stack<string>();
Console.WriteLine(bare.TryPeek(out string nothing));
Console.WriteLine(nothing == null);
}
}
Output
True
red
1
False
True
How It Works
An item is found. The stack has one plate, so TryPeek returns True and puts "red" into top.
Still there. The printed Count is 1. The plate was only looked at, not lifted.
A bare stack. A brand-new stack has no top, so the second call prints False and does not throw.
The default fills in. No item was found, so nothing is null, the default for string, and the last line is True.
Example 2 — A Helper That Names the Current Page
Wrap TryPeek in a small method and call it as pages are closed one by one, until none is left.
C#
using System;
using System.Collections.Generic;
class Program {
static string Describe(Stack<string> pages) {
if (pages.TryPeek(out string page)) {
return "Now on: " + page;
}
return "No page open";
}
static void Main() {
Stack<string> pages = new Stack<string>();
pages.Push("home");
pages.Push("about");
Console.WriteLine(Describe(pages));
pages.Pop();
Console.WriteLine(Describe(pages));
pages.Pop();
Console.WriteLine(Describe(pages));
}
}
Output
Now on: about
Now on: home
No page open
How It Works
One method for every case.Describe works for any stack, even an empty one, because TryPeek never throws.
Branch on the bool. When the call returns true, the method uses page; otherwise it returns a fixed message.
Closing a page. Each Pop() in Main removes the current page, so the second call sees home on top.
Ends bare. After the second pop nothing is on the stack, and the third call reports No page open.
Example 3 — Pop Only While the Top Passes a Test
Use TryPeek to read the top number. Pop it only while it is small, then stop and keep the rest.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<int> numbers = new Stack<int>(new int[] { 3, 9, 4, 2 });
int total = 0;
while (numbers.TryPeek(out int top) && top <= 4) {
numbers.Pop();
total += top;
}
Console.WriteLine(total);
Console.WriteLine(numbers.Count);
Console.WriteLine(numbers.Peek());
}
}
Output
6
2
9
How It Works
Array order matters. The constructor pushes the array in order, so 2, the last element, ends up on top, with 9 and 3 further down.
Two pass. The top is 2, then 4. Both are 4 or less, so both are popped and total becomes 6.
The blocker. The new top is 9, which is above 4. The condition fails and the loop stops. The 3 below it is never reached.
A stack cannot skip. It only gives up its top, so the small 3 stays buried. Count is 2 and Peek() shows 9.
Frequently Asked Questions
It tries to read the top item without removing it. 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.
Peek throws InvalidOperationException on an empty stack. TryPeek returns false instead. Neither of them removes the item.
No. The item stays on top of the stack and Count does not change.
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, check Count before calling Peek.
It is the default value of the item type, such as null for string or 0 for int. Do not treat it as real data; always read the bool first.