Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to safely dequeue an element in a C# queue

Surabhi Sharma

The Queue<T> generic class in the System.Collections.Generic namespace provides the TryDequeue() method, which is used to safely dequeue from the queue.

We can use the TryDequeue() method to avoid the exception thrown if an empty queue is dequeued.


public bool TryDequeue (out T result);

This method removes the element at the beginning of the Queue<T>, and it is copied to the result parameter.

It returns true if the element is removed successfully from the Queue<T> and false if the queue is empty.

Things to note

  • The method returns false but does not throw an exception if the queue is empty and Dequeue() is called.

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

  • This method modifies the state of the queue.


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 TryDequeue() method on the queue which removes and copies the first item of the queue to the item variable declared above. Now the queue is empty, as it had only one element, which is removed with TryDequeue().

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

We print all the elements of the queue again after the TryDequeue() 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>();

        Console.WriteLine("Enqueued elements to the Queue \nQueue Items : {0}", string.Join(",", months.ToArray()));
        string item=string.Empty;
        if(months.TryDequeue(out item)) {        
          Console.WriteLine($"Removed {item} safely from the Queue using TryDequeue()");

        if(months.TryDequeue(out item)) {        
          Console.WriteLine($"Removed {item} safely from the Queue using TryDequeue()");
        } else
          Console.WriteLine("Queue is Empty!");

        Console.WriteLine("Queue Items After TryDequeue() : {0}", string.Join(",", months.ToArray()));

TryDequeue() 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



View all Courses

Keep Exploring