C# Queue

Introduction

The Queue<T> class in C# represents a first-in, first-out (FIFO) collection of objects. It is part of the System.Collections.Generic namespace and is useful when you need to process elements in the order they were added. The Queue<T> class provides methods to enqueue, dequeue, and peek at items, ensuring efficient management of FIFO collections.

Key Features of Queue

  • FIFO Order: First-in, first-out ordering of elements.
  • Dynamic Size: Automatically resizes as elements are added or removed.
  • Type Safety: Enforces type safety, ensuring that all elements are of the specified type T.
  • Rich API: Includes methods for enqueuing, dequeuing, and peeking at elements.

Creating a Queue

Declaration and Initialization

You can declare and initialize a Queue<T> in several ways:

Example

using System;
using System.Collections.Generic;

namespace QueueExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating an empty queue
            Queue<int> numbers = new Queue<int>();

            // Creating a queue with initial elements
            Queue<string> fruits = new Queue<string>(new[] { "Apple", "Banana", "Cherry" });

            // Enqueuing elements to the queue
            numbers.Enqueue(1);
            numbers.Enqueue(2);
            numbers.Enqueue(3);

            // Displaying elements
            Console.WriteLine("Fruits in queue:");
            foreach (string fruit in fruits)
            {
                Console.WriteLine(fruit);
            }
        }
    }
}

Output

Fruits in queue:
Apple
Banana
Cherry

Common Operations on Queue

Enqueuing Elements

  • Enqueue: Adds an element to the end of the queue.
numbers.Enqueue(4);

Dequeuing Elements

  • Dequeue: Removes and returns the element at the beginning of the queue. Throws an InvalidOperationException if the queue is empty.
int frontNumber = numbers.Dequeue(); // 1

Peeking at Elements

  • Peek: Returns the element at the beginning of the queue without removing it. Throws an InvalidOperationException if the queue is empty.
int frontNumber = numbers.Peek(); // 2

Checking the Queue Size

  • Count: Gets the number of elements in the queue.
int count = numbers.Count; // 2

Clearing the Queue

  • Clear: Removes all elements from the queue.
numbers.Clear();

Practical Example

Let’s create a practical example where we use a Queue<T> to manage a print queue in a print server application.

Example

using System;
using System.Collections.Generic;

namespace PrintQueueExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue<string> printQueue = new Queue<string>();

            // Adding print jobs to the queue
            AddPrintJob(printQueue, "Document1.pdf");
            AddPrintJob(printQueue, "Photo.jpg");
            AddPrintJob(printQueue, "Spreadsheet.xlsx");

            // Processing print jobs
            ProcessPrintJobs(printQueue);
        }

        static void AddPrintJob(Queue<string> queue, string job)
        {
            queue.Enqueue(job);
            Console.WriteLine($"Added print job: {job}");
        }

        static void ProcessPrintJobs(Queue<string> queue)
        {
            Console.WriteLine("Processing print jobs...");
            while (queue.Count > 0)
            {
                string job = queue.Dequeue();
                Console.WriteLine($"Printing: {job}");
            }
        }
    }
}

Output

Added print job: Document1.pdf
Added print job: Photo.jpg
Added print job: Spreadsheet.xlsx
Processing print jobs...
Printing: Document1.pdf
Printing: Photo.jpg
Printing: Spreadsheet.xlsx

Conclusion

The Queue<T> class in C# provides a simple and efficient way to manage collections of items in a first-in, first-out (FIFO) order. It is ideal for scenarios where you need to process elements in the order they were added, such as print queues, task scheduling, and buffering. Understanding how to use Queue<T> effectively can help you manage collections of data in your applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top