ZetCode

C# Queue

last modified October 5, 2026

This article explains how to use the generic Queue<T> collection in C#. A queue processes items in first-in, first-out (FIFO) order: the item added earliest is removed first.

Creating a queue

Queue<T> is in the System.Collections.Generic namespace. A queue grows as items are added. The following example creates a queue of strings and adds three values with Enqueue.

Program.cs
using System.Collections.Generic;

var tasks = new Queue<string>();
tasks.Enqueue("compile");
tasks.Enqueue("test");
tasks.Enqueue("package");

foreach (var task in tasks)
{
    Console.WriteLine(task);
}
$ dotnet run
compile
test
package

Enumeration visits items from the front of the queue to the back. It does not remove them.

Reading and removing items

Peek returns the next item without changing the queue. Dequeue returns and removes that item. Check Count or use TryDequeue when the queue might be empty; calling Peek or Dequeue on an empty queue throws an InvalidOperationException.

Program.cs
var numbers = new Queue<int>();
numbers.Enqueue(10);
numbers.Enqueue(20);
numbers.Enqueue(30);

Console.WriteLine($"Next: {numbers.Peek()}");
Console.WriteLine($"Removed: {numbers.Dequeue()}");

if (numbers.TryDequeue(out int next))
{
    Console.WriteLine($"Removed: {next}");
}

Console.WriteLine($"Remaining: {numbers.Count}");
$ dotnet run
Next: 10
Removed: 10
Removed: 20
Remaining: 1

Processing a queue

A queue is useful when work should be handled in arrival order. A loop can process every item until the queue is empty.

Program.cs
var requests = new Queue<string>();
requests.Enqueue("request A");
requests.Enqueue("request B");
requests.Enqueue("request C");

while (requests.TryDequeue(out string? request))
{
    Console.WriteLine($"Handling {request}");
}

Console.WriteLine($"Queue size: {requests.Count}");
$ dotnet run
Handling request A
Handling request B
Handling request C
Queue size: 0

TryDequeue is available in modern .NET versions and avoids a separate empty check. The nullable annotation shown is appropriate when nullable reference types are enabled.

Initializing and clearing a queue

A queue can be initialized from an existing sequence. Use Clear to remove every item.

Program.cs
var colors = new Queue<string>(new[] { "red", "green", "blue" });
Console.WriteLine(colors.Count);

colors.Clear();
Console.WriteLine(colors.Count);
$ dotnet run
3
0

Queue or another collection?

Use Queue<T> when elements should leave in the order they arrive. A Stack<T> removes the most recently added item first (LIFO). If you need to access items by index or insert them in the middle, a list is usually a better fit. Queue operations at the ends are typically constant time.

Source

Queue<T> Class - .NET API

This article introduced the FIFO queue collection in C#.

Author

Jan Bodnar writes programming tutorials and educational content.

List all C# tutorials.