How to Use Queue in C#: Syntax and Examples
In C#, use the
Queue<T> class to store items in a first-in, first-out (FIFO) order. You add items with Enqueue() and remove them with Dequeue(). The Peek() method lets you see the next item without removing it.Syntax
The Queue<T> class is a generic collection that stores elements in FIFO order. You create a queue with new Queue<T>(). Use Enqueue(item) to add an item, Dequeue() to remove and return the oldest item, and Peek() to view the oldest item without removing it.
csharp
Queue<string> queue = new Queue<string>(); queue.Enqueue("item1"); string first = queue.Dequeue(); string next = queue.Peek();
Example
This example shows how to create a queue, add items, remove them, and peek at the next item. It prints the queue state after each operation.
csharp
using System; using System.Collections.Generic; class Program { static void Main() { Queue<string> queue = new Queue<string>(); // Add items queue.Enqueue("apple"); queue.Enqueue("banana"); queue.Enqueue("cherry"); Console.WriteLine("Queue after enqueue: " + string.Join(", ", queue)); // Peek at the first item Console.WriteLine("Peek: " + queue.Peek()); // Remove items Console.WriteLine("Dequeue: " + queue.Dequeue()); Console.WriteLine("Queue after dequeue: " + string.Join(", ", queue)); // Remove another item Console.WriteLine("Dequeue: " + queue.Dequeue()); Console.WriteLine("Queue after dequeue: " + string.Join(", ", queue)); } }
Output
Queue after enqueue: apple, banana, cherry
Peek: apple
Dequeue: apple
Queue after dequeue: banana, cherry
Dequeue: banana
Queue after dequeue: cherry
Common Pitfalls
One common mistake is calling Dequeue() or Peek() on an empty queue, which throws an InvalidOperationException. Always check queue.Count before removing or peeking. Another pitfall is confusing Queue<T> with Stack<T>, which uses last-in, first-out (LIFO) order.
csharp
Queue<int> queue = new Queue<int>(); // Wrong: Dequeue on empty queue throws exception // int item = queue.Dequeue(); // Throws InvalidOperationException // Right: Check count before dequeue if (queue.Count > 0) { int item = queue.Dequeue(); Console.WriteLine(item); } else { Console.WriteLine("Queue is empty."); }
Output
Queue is empty.
Quick Reference
| Method | Description |
|---|---|
| Enqueue(T item) | Adds an item to the end of the queue. |
| Dequeue() | Removes and returns the item at the front of the queue. |
| Peek() | Returns the item at the front without removing it. |
| Count | Gets the number of items in the queue. |
| Clear() | Removes all items from the queue. |
Key Takeaways
Use Queue to store items in first-in, first-out order in C#.
Add items with Enqueue(), remove with Dequeue(), and view next item with Peek().
Always check Count before calling Dequeue() or Peek() to avoid exceptions.
Queue is different from Stack; it processes items in FIFO order.
Use Clear() to empty the queue when needed.