In C#, Queue.TryPeek(out result) is the safe version of Peek(). If the queue has an item, it copies the front item into the out variable and returns true. If the queue is empty, it returns false and does not throw. In both cases the queue is left unchanged.
It is a quick question to the counter clerk: "Is anybody next, and who?" The clerk answers yes with a name, or no. Nobody leaves the line. To also take the person out, use TryDequeue().
This is an instance member of Queue<T> (System.Collections.Generic). Call it on a queue variable, such as line.TryPeek(...). A Queue<T> is a class, so two variables can share one queue. It is first in, first out (FIFO): items leave in the order they arrived. It is not thread-safe; for several threads use ConcurrentQueue<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#
Queue<string> line = new Queue<string>();
line.Enqueue("Asha");
if (line.TryPeek(out string front)) {
// front is "Asha"; she is still in the queue
}
bool has = new Queue<string>().TryPeek(out string none); // false
Call
What it does
line.TryPeek(out string front)
If the queue has items: stores the front item in front and returns true. Nothing is removed.
line.TryPeek(out string front) (empty)
Returns false. front gets the default value (null for strings, 0 for int).
line.TryPeek(out _)
Use a discard when you only care whether something is waiting, not what it is.
Decide with the bool, not with the out value. A queue of int may hold a real 0, and an empty queue also gives 0. TryPeek is O(1). Classic .NET Framework does not have it; there you can write queue.Count > 0 ? queue.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 front item. When it returns false, it holds the default value of T.
Return Value
Return Value
Description
bool
true if the queue has at least one item and the front item was copied to result. false if the queue is empty.
C# Examples
Example 1 — Peek Without Throwing
Peek at a one-item queue, then at an empty queue, and compare the bool results and the Count.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Queue<string> line = new Queue<string>();
line.Enqueue("Asha");
bool found = line.TryPeek(out string front);
Console.WriteLine(found);
Console.WriteLine(front);
Console.WriteLine(line.Count);
Queue<string> empty = new Queue<string>();
Console.WriteLine(empty.TryPeek(out string nothing));
Console.WriteLine(nothing == null);
}
}
Output
True
Asha
1
False
True
How It Works
Item found. The line has one person, so TryPeek returns True and puts "Asha" into front.
Still waiting. The printed Count is 1. Asha was only looked at, not removed.
Empty queue. A brand-new queue has no front, so the second call prints False and does not throw.
Default fills in. Because no item was found, nothing is null, the default for string, and the last line is True.
Example 2 — A Helper That Reports the Next Person
Wrap TryPeek in a small method and call it as the queue changes from full to empty.
C#
using System;
using System.Collections.Generic;
class Program {
static string NextUp(Queue<string> line) {
if (line.TryPeek(out string who)) {
return "Next: " + who;
}
return "Queue is empty";
}
static void Main() {
Queue<string> line = new Queue<string>();
line.Enqueue("Ben");
line.Enqueue("Chitra");
Console.WriteLine(NextUp(line));
line.Dequeue();
Console.WriteLine(NextUp(line));
line.Dequeue();
Console.WriteLine(NextUp(line));
}
}
Output
Next: Ben
Next: Chitra
Queue is empty
How It Works
One method, no exception.NextUp works for any queue, even an empty one, because TryPeek never throws.
Branch on the bool. When the call returns true, the method uses who; otherwise it returns a fixed message.
Move the line forward. Each Dequeue() in Main removes the front, so the second call sees Chitra.
Ends empty. After the second dequeue, the third call finds no front and reports Queue is empty.
Example 3 — Take Items Only While They Pass a Test
Use TryPeek to check the front number. Remove it only while it is small enough, then stop and keep the rest.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Queue<int> numbers = new Queue<int>(new int[] { 2, 4, 6, 20, 3 });
int total = 0;
while (numbers.TryPeek(out int next) && next <= 10) {
numbers.Dequeue();
total += next;
}
Console.WriteLine(total);
Console.WriteLine(numbers.Count);
Console.WriteLine(numbers.Peek());
}
}
Output
12
2
20
How It Works
Test, then act. The loop condition first peeks at the front. Only if there is a front item and it is 10 or less does the body run.
Three pass. The numbers 2, 4, and 6 pass the test and are dequeued, so total becomes 12.
The blocker. The front is now 20, which is above 10. The condition fails, and 20 stays in the queue, even though 3 is behind it.
A queue cannot skip. It only serves from the front, so 3 cannot be taken before 20. Count is 2 and Peek() shows 20.
Frequently Asked Questions
It tries to read the front item without removing it. If the queue has an item, it returns true and gives the item in the out parameter. If the queue is empty, it returns false.
Peek throws InvalidOperationException on an empty queue. TryPeek returns false instead. Neither of them removes the item.
No. The item stays at the front of the queue 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.