The Queue<T> class in C# is part of the System.Collections.Generic namespace and implements a first-in, first-out (FIFO) collection, where the first element added is the first one to be removed.
This makes queues useful when you need to process elements in the order they were added, such as handling tasks, orders, or messages.
The key operations in a queue are Enqueue (to add an item) and Dequeue (to remove and retrieve the oldest item).
In this tutorial, we’ll cover:
1. Creating a Queue<T>
To create a Queue<T>, include the System.Collections.Generic namespace. T is the type parameter representing the type of elements in the queue, such as int, string, or a custom class.
using System; using System.Collections.Generic; class Program { static void Main() { // Create an empty queue of integers Queue<int> numberQueue = new Queue<int>(); // Create a queue of strings with initial values Queue<string> nameQueue = new Queue<string>(new string[] { "Alice", "Bob", "Charlie" }); Console.WriteLine("Initial name queue:"); foreach (string name in nameQueue) { Console.WriteLine(name); } } }
Output:
Initial name queue: Alice Bob Charlie
In this example:
- Queue<int> numberQueue = new Queue<int>(); creates an empty queue of integers.
- Queue<string> nameQueue = new Queue<string>(new string[] { “Alice”, “Bob”, “Charlie” }); initializes a queue of strings with initial values, with “Alice” being at the front.
2. Adding Elements with Enqueue
You can add elements to a queue using the Enqueue method. Each item is added to the end of the queue.
using System; using System.Collections.Generic; class Program { static void Main() { Queue<int> numberQueue = new Queue<int>(); // Adding elements numberQueue.Enqueue(10); numberQueue.Enqueue(20); numberQueue.Enqueue(30); Console.WriteLine("Queue after enqueuing elements:"); foreach (int number in numberQueue) { Console.WriteLine(number); } } }
Output:
Queue after enqueuing elements: 10 20 30
In this example:
- The Enqueue method adds elements to the end of the queue in FIFO order. The first item added (10) will be the first item to be removed.
3. Retrieving and Removing Elements with Dequeue
You can remove and retrieve the front element of the queue using the Dequeue method.
using System; using System.Collections.Generic; class Program { static void Main() { Queue<int> numberQueue = new Queue<int>(new int[] { 10, 20, 30 }); // Remove and retrieve the front element int frontElement = numberQueue.Dequeue(); Console.WriteLine("Dequeued element: " + frontElement); Console.WriteLine("Queue after dequeuing:"); foreach (int number in numberQueue) { Console.WriteLine(number); } } }
Output:
Dequeued element: 10 Queue after dequeuing: 20 30
In this example:
- Dequeue removes the front element (10) from the queue and returns it.
- After Dequeue, the queue no longer contains 10, with 20 as the new front element.
Note: Attempting to Dequeue from an empty queue will throw an InvalidOperationException.
4. Retrieving the Front Element with Peek
The Peek method allows you to view the front element without removing it from the queue.
using System; using System.Collections.Generic; class Program { static void Main() { Queue<int> numberQueue = new Queue<int>(new int[] { 10, 20, 30 }); // Retrieve the front element without removing it int frontElement = numberQueue.Peek(); Console.WriteLine("Front element (Peek): " + frontElement); Console.WriteLine("Queue after Peek (unchanged):"); foreach (int number in numberQueue) { Console.WriteLine(number); } } }
Output:
Front element (Peek): 10 Queue after Peek (unchanged): 10 20 30
In this example:
- Peek returns the front element (10) without removing it, leaving the queue unchanged.
Note: Attempting to Peek from an empty queue will throw an InvalidOperationException.
5. Checking the Number of Elements and Clearing the Queue
You can check the number of elements in a queue using Count and clear all elements using Clear.
using System; using System.Collections.Generic; class Program { static void Main() { Queue<int> numberQueue = new Queue<int>(new int[] { 10, 20, 30 }); // Check the number of elements Console.WriteLine("Count: " + numberQueue.Count); // Clear all elements from the queue numberQueue.Clear(); Console.WriteLine("Count after clearing: " + numberQueue.Count); } }
Output:
Count: 3 Count after clearing: 0
In this example:
- Count returns the number of elements in the queue.
- Clear removes all elements, resulting in an empty queue with a Count of 0.
6. Iterating Through a Queue
You can iterate through a queue using a foreach loop. The items are iterated in FIFO order, starting from the front.
using System; using System.Collections.Generic; class Program { static void Main() { Queue<string> nameQueue = new Queue<string>(new string[] { "Alice", "Bob", "Charlie" }); Console.WriteLine("Iterating through the queue:"); foreach (string name in nameQueue) { Console.WriteLine(name); } } }
Output:
Iterating through the queue: Alice Bob Charlie
In this example:
- The foreach loop iterates over the queue from the front element to the end in FIFO order.
7. Practical Examples of Queue<T> in Real Scenarios
Example 1: Customer Service Queue
A Queue<T> can represent a line of customers waiting for service. Each customer is served in the order they joined the queue.
using System; using System.Collections.Generic; class Program { static void Main() { Queue<string> customerQueue = new Queue<string>(); // Customers join the queue customerQueue.Enqueue("Customer 1"); customerQueue.Enqueue("Customer 2"); customerQueue.Enqueue("Customer 3"); Console.WriteLine("Serving customers:"); // Serve each customer in FIFO order while (customerQueue.Count > 0) { string customer = customerQueue.Dequeue(); Console.WriteLine("Serving " + customer); } } }
Output:
Serving customers: Serving Customer 1 Serving Customer 2 Serving Customer 3
In this example:
- Enqueue adds customers to the queue.
- Dequeue serves each customer in the order they joined.
Example 2: Task Scheduling
A Queue<T> can be used to manage tasks in the order they are added, ensuring tasks are processed in a FIFO manner.
using System; using System.Collections.Generic; class Program { static void Main() { Queue<string> taskQueue = new Queue<string>(); // Add tasks to the queue taskQueue.Enqueue("Task 1"); taskQueue.Enqueue("Task 2"); taskQueue.Enqueue("Task 3"); Console.WriteLine("Processing tasks:"); // Process each task in FIFO order while (taskQueue.Count > 0) { string task = taskQueue.Dequeue(); Console.WriteLine("Processing " + task); } } }
Output:
Processing tasks: Processing Task 1 Processing Task 2 Processing Task 3
In this example:
- Enqueue adds tasks to the queue, and Dequeue processes them in the order they were added.
Summary
In this tutorial, we covered the Queue<T> class in C# and demonstrated its features:
- Creating a Queue<T>: Initializing queues with or without initial values.
- Adding Elements: Using Enqueue to add items to the end.
- Retrieving and Removing Elements: Using Dequeue to remove and retrieve the front item.
- Retrieving the Front Element: Using Peek to look at the front item without removing it.
- Checking the Number of Elements and Clearing the Queue: Using Count and Clear.
- Iterating Through a Queue: Using foreach to iterate from front to back.
- Practical Examples: Representing customer service and task scheduling queues.
The Queue<T> class is a powerful collection type in C# that simplifies working with FIFO data structures, making it ideal for scenarios that require ordered processing, such as task scheduling and customer service queues.