How to dequeue an element from a C# Queue

The Queue<T> generic class in the System.Collections.Generic namespace provides the Dequeue() method, which is used to remove and return an element from the beginning of the Queue<T>.

Syntax

public T Dequeue ();

Things to note

  • This method removes and returns the element present at the beginning of the queue.
  • It throws an Invalid operation 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.

Example

In this example, we have created a queue of strings and enqueued a few month names to it. We then print all the items of the queue.

Notice that all the elements are inserted to the end of the queue as Queue is a FIFOFirst In First Out data structure.

We then use the Dequeue method to remove the first two elements from the beginning of the queue.

We print all the elements of the queue again after the Dequeue() operation. We can observe in the output that the top two elements, January and February, are removed from the beginning of the queue.

using System;
using System.Collections.Generic;
class QueueTest
{
static void Main()
{
Queue<string> months = new Queue<string>();
months.Enqueue("January");
months.Enqueue("February");
months.Enqueue("March");
months.Enqueue("April");
months.Enqueue("May");
months.Enqueue("June");
Console.WriteLine("Enqueued elements to the Queue \nQueue Items : {0}", string.Join(",", months.ToArray()));
string firtItem = months.Dequeue();
string secondItem = months.Dequeue();
Console.WriteLine($"Removed {firtItem} and {secondItem} from the Queue using Dequeue()");
Console.WriteLine("Queue Items After Dequeue() : {0}", string.Join(",", months.ToArray()));
}
}