Queues

A Queue<T> hands values back in the order they arrived, first in, first out. Enqueue adds to the back of the line, Dequeue takes from the front, and Peek looks without taking.

Journeyman · C# · Updated

After this lesson you can

  • Use a Queue<T> for first-in, first-out work, with Enqueue, Dequeue, Peek and TryDequeue

Key takeaways

  • A Queue<T> is first in, first out (FIFO): values come back in the order they were added.
  • Enqueue adds to the back, Dequeue removes and returns the front, and Peek returns the front without removing it.
  • Dequeue and Peek on an empty queue throw an InvalidOperationException, so check Count first or use TryDequeue.
  • Use a queue when work should be handled in the order it arrived, such as customers in line or a waiting list.

A Queue<T> works like a line at a café counter: the first person to join the line is the first one served. That's first in, first out, or FIFO.

You don't reach into a queue by position. You add at the back, and take from the front.

Enqueue and Dequeue

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

line.Enqueue("Emily");
line.Enqueue("Lucas");
line.Enqueue("Sophia");

Console.WriteLine(quot;Next up: {line.Peek()}");

while (line.Count > 0)
{
    string customer = line.Dequeue();
    Console.WriteLine(quot;Serving {customer}");
}
Next up: Emily
Serving Emily
Serving Lucas
Serving Sophia
Member Does
Enqueue(value) Adds the value to the back of the line
Dequeue() Removes the value at the front, and returns it
Peek() Returns the value at the front, without removing it
Count How many values are waiting
TryDequeue(out value) Like Dequeue, but returns false instead of failing when the queue is empty

An empty queue

Dequeue() and Peek() on an empty queue throw an InvalidOperationException:

Queue<string> line = new Queue<string>();
string next = line.Dequeue();
Unhandled exception. System.InvalidOperationException: Queue empty.

So check Count first, as the while loop above does, or use TryDequeue, which returns false when there's no one waiting:

Queue<string> waitingList = new Queue<string>();
waitingList.Enqueue("Mason");

for (int seat = 1; seat <= 2; seat++)
{
    if (waitingList.TryDequeue(out string? name))
    {
        Console.WriteLine(quot;Seat {seat} goes to {name}");
    }
    else
    {
        Console.WriteLine(quot;Seat {seat} is open: nobody is waiting");
    }
}
Seat 1 goes to Mason
Seat 2 is open: nobody is waiting

Where queues fit

Use a queue whenever work should be handled in the order it arrived: customers in line, orders waiting to be made, emails waiting to be sent, a waiting list for a sold-out show.

Check yourself

1 question to try on the lesson page.

So what

A queue makes "first come, first served" automatic: nobody can cut in line, and nobody gets skipped. When the order things arrive in is the order they should be handled, use a queue.

Key terms

Cheat sheets