C# Queue Example: First-In, First-Out Collections

A queue hands items back in the order they arrived: first in, first out (FIFO), like people waiting at a counter. Use one for work that should be processed in arrival order: print jobs, messages, or the frontier of a breadth-first search.

Use the generic Queue<T> from System.Collections.Generic. The non-generic System.Collections.Queue is covered briefly at the end for legacy code.

Enqueue, dequeue and peek

var queue = new Queue<string>();
queue.Enqueue("Obj1");
queue.Enqueue("Obj2");
queue.Enqueue("Obj3");

Console.WriteLine($"Count: {queue.Count}");
foreach (string item in queue)
{
    Console.WriteLine(item);
}

string first = queue.Dequeue();
Console.WriteLine($"Dequeued: {first}");

Console.WriteLine($"Contains Obj1: {queue.Contains("Obj1")}");
Console.WriteLine($"Contains Obj2: {queue.Contains("Obj2")}");

Output:

Count: 3
Obj1
Obj2
Obj3
Dequeued: Obj1
Contains Obj1: False
Contains Obj2: True

Enqueue adds an item at the back. Dequeue removes and returns the item at the front, which is the oldest one, not the newest. Peek returns the front item without removing it. Enumerating with foreach goes from front to back and leaves the queue unchanged.

Enqueue and Dequeue are O(1). Internally, Queue<T> uses a circular buffer, so removing from the front does not shift the other items the way list.RemoveAt(0) would. That is the main reason to prefer a queue over a List<T> for this job.

Avoiding the empty-queue exception

Dequeue and Peek throw InvalidOperationException when the queue is empty. TryDequeue and TryPeek (since .NET Core 2.0) return false instead, which makes the common “process until empty” loop short:

while (queue.TryDequeue(out string? item))
{
    Console.WriteLine($"Processing {item}");
}

When order depends on priority: PriorityQueue

Sometimes the next item should be the most urgent one, not the oldest. .NET 6 added PriorityQueue<TElement, TPriority>, which always dequeues the element with the lowest priority value:

var jobs = new PriorityQueue<string, int>();
jobs.Enqueue("Send newsletter", 3);
jobs.Enqueue("Fix production bug", 1);
jobs.Enqueue("Update docs", 2);

while (jobs.TryDequeue(out string? job, out int priority))
{
    Console.WriteLine($"{priority}: {job}");
}

Output:

1: Fix production bug
2: Update docs
3: Send newsletter

Two traps here. Elements with equal priority do not come out in insertion order, so if ties matter, make the priority a tuple such as (priority, sequenceNumber). And enumerating a PriorityQueue (through its UnorderedItems property) does not return items in priority order; only dequeuing does.

Queues shared between threads

Queue<T> is not thread-safe. If one thread enqueues while another dequeues, use ConcurrentQueue<T> from System.Collections.Concurrent. It has the same Enqueue and TryDequeue methods and needs no locks.

For a producer and consumer setup, look at System.Threading.Channels before reaching for ConcurrentQueue<T>. A channel lets the consumer await the next item instead of polling in a loop, and a bounded channel slows the producer down when the consumer falls behind.

The legacy non-generic Queue

Older code uses System.Collections.Queue, which stores everything as object:

using System.Collections;

Queue queue = new Queue();
queue.Enqueue("Obj1");
queue.Enqueue("Obj2");

object obj = queue.Dequeue();   // "Obj1", the first item added
string text = (string)obj;

It works the same way, but value types are boxed and every read needs a cast. Note that Dequeue returns the first item added, not the last, whichever version you use. Swapping it for Queue<T> is usually a mechanical change.

Related examples

Leave a Comment