C# Generic Queue

Similarly to a non-generic queue, a generic queue can be described as a first-in first-out data structure, or FIFO for short. New elements are added to the bottom or end of the queue and the item at the front of the queue is available to be removed first. Generic queues however, must have the type of data specified at the time of declaration.

Below is an example of how a queue, called ‘people’, that contains string values, can be declared.

Queue<string> people = new Queue<string>();

In order to add items to a queue, the ‘Enqueue’ method must be used.


Here, four names have been added to the queue.

It is possible to see how many items there are in the queue using the ‘Count’ property of the queue itself.


In order to see the items in a generic queue, without actually removing them, a ‘foreach’ loop can be used.

foreach (string person in people)

This will display each name in the queue on a separate line in the console.


If it is required to see just the next item in the queue without removing it, then the ‘Peek’ method can be used.


As well as being able to see the next item, there is also the functionality to check to see if a particular value exists in a queue. This is achieved using the ‘Contains’ method.


The above example checks to see if the value, ‘George’, exists in the queue and returns a Boolean 'True' or 'False' value.

In order to remove individual items from a queue, the ‘Dequeue’ method can be utilised. The example below assigns the number of items in the queue to a variable. This value is then used to limit the number of iterations in a ‘for’ loop. Within the loop the ‘Dequeue’ method is used to remove an item from the queue, display it in the console and output the number of items left in the queue.

Queue<string> people = new Queue<string>();


int queueLength = people.Count;

Console.WriteLine("Items in queue: {0}", queueLength);

for (int i = 1; i <= queueLength; i++)

   Console.WriteLine("Next item from queue: {0}", people.Dequeue());
   Console.WriteLine("Items left in queue: {0}", people.Count);


The resulting output is shown below.

Items in queue: 4

Next item from queue: Bob
Items left in queue: 3

Next item from queue: George
Items left in queue: 2

Next item from queue: Fred
Items left in queue: 1

Next item from queue: Alan
Items left in queue: 0

Finally, if it is necessary to remove all items in a queue in one go, instead of individually with the ‘Dequeue’ method, there is a ‘Clear’ method to accomplish this.


Further Reading