How to safely peek in a queue in C#

The Queue<T> generic class in the System.Collections.Generic namespace provides the TryPeek() method, which is used to safely get the element at the beginning of the queue without removing it.

With the TryPeek() method, we can avoid the exception thrown if we get the beginning element for an empty queue.

Syntax

public bool TryPeek (out T result);

If there is an element present at the beginning of the queue, this method returns true and copies the element to the result parameter.

It returns false for an empty queue, and the result parameter contains the default value of T.

Things to note

  • It returns false but does not throw an exception if the queue is empty and TryPeek() is called.

  • The time complexity of this method is O(1)O(1).

  • This method does not modify the state of the queue.

  • This method is only available in the .Net 5.0 onwards, .Net Core 2.0 onwards, and .Net standard 2.1.

Code

In this example, we create a queue of strings and enqueue a single string to it. We then print all the items of the queue.

We then call the TryPeek() method on the queue. It returns true and copies the first item of the queue to the item variable declared above. The count of element does not change in the queue, as TryPeek() does not change the state of the queue.

We call the Clear() method on the queue to make it empty.

Now, we again call the TryPeek() method on an empty queue, and it returns false. We use the false value to print the Queue is empty! message. It would have thrown an exception if we used Peek() on this empty queue.

We print all the elements of the queue again after the TryPeek() operation and observe that the queue is empty.

using System;
using System.Collections.Generic;
class QueueTest
{
static void Main()
{
Queue<string> months = new Queue<string>();
months.Enqueue("January");
Console.WriteLine("Enqueued elements to the Queue \nQueue Items : {0}", string.Join(",", months.ToArray()));
string item = string.Empty;
if (months.TryPeek(out item))
{
Console.WriteLine($"Peeked {item} safely from the Queue using TryPeek()");
}
Console.WriteLine("Clearing the Queue using Clear()");
months.Clear();
if (months.TryPeek(out item))
{
Console.WriteLine($"Peeked {item} safely from the Queue using TryPeek()");
}
else
{
Console.WriteLine("Safely Peeked again using TryPeek() and found Queue is Empty!");
}
Console.WriteLine("Queue Items After TryPeek() : {0}", string.Join(",", months.ToArray()));
}
}

TryPeek() is available in the newer versions of .NET, such as:

  • .NET 5.0, 6.0 Preview 6
  • NET Core 2.0, 2.1, 2.2, 3.0, 3.1
  • .NET Standard 2.1

Free Resources