Working with Queues in C#: Implementing First-In, First-Out (FIFO) Data Structures

This tutorial provides a comprehensive guide to using C#'s `Queue` class for managing FIFO (First-In, First-Out) collections. It covers adding elements (`Enqueue`), removing elements (`Dequeue`), accessing elements, and iterating through a queue, demonstrating its application in various programming scenarios.



Working with Queues in C#

Introduction

The `Queue` class in C# implements a queue data structure. Queues follow the FIFO (First-In, First-Out) principle: the first element added is the first element removed. Unlike stacks, queues allow duplicate elements.

Key Features of `Queue`

  • FIFO Ordering: Elements are processed in the order they were added.
  • Duplicate Elements Allowed: You can add the same element multiple times.
  • Dynamic Sizing: The queue automatically grows or shrinks as needed.
  • Namespace: `System.Collections.Generic`

Example: Using `Queue`

This example shows how to add elements (Enqueue), remove elements (Dequeue), and iterate through a queue:

Example: Queue Operations

using System;
using System.Collections.Generic;

public class QueueExample {
    public static void Main(string[] args) {
        Queue<string> names = new Queue<string>();
        names.Enqueue("Sonoo");
        names.Enqueue("Peter");
        names.Enqueue("James");
        names.Enqueue("Ratan");
        names.Enqueue("Irfan");

        foreach (string name in names) {
            Console.WriteLine(name);
        }

        Console.WriteLine($"Peek element: {names.Peek()}"); //Looks at the next item without removing it
        Console.WriteLine($"Dequeue: {names.Dequeue()}"); //Removes and returns the next item
        Console.WriteLine($"After Dequeue, Peek element: {names.Peek()}");
    }
}
Example Output

Sonoo
Peter
James
Ratan
Irfan
Peek element: Sonoo
Dequeue: Sonoo
After Dequeue, Peek element: Peter
        

Conclusion

The `Queue` class is a simple yet effective way to manage collections of items in a FIFO manner in C#. Its dynamic sizing and straightforward API make it well-suited for various applications where maintaining the order of elements is important.