C# Queue

A Queue works on the principle of First In, First Out (FIFO). The first element added to the queue is the first one to be removed.

Feature of Queue

Enqueue: Adds an element to the back (end) of the queue.

Dequeue: Removes and returns the element from the front of the queue.

Peek: Returns the element at the front of the queue without removing it.

Count: Returns the number of elements in the queue.

Example:


using System;
using System.Collections.Generic;

class MyProgram
{
    static void Main()
    {
        // Create a new Queue of strings 
        Queue taskQueue = new Queue();
        taskQueue.Enqueue("Task1");
        taskQueue.Enqueue("Task2");
        taskQueue.Enqueue("Task3");
        taskQueue.Enqueue("Task4");

        // Count the items in Queue
        int itemsInQueue = taskQueue.Count;
        Console.WriteLine("Count the items in Queue is "+itemsInQueue);
        // Delete one item which firstly added in Queue.
        string firstTask = taskQueue.Dequeue();  // Remove and get the first task
        Console.WriteLine("First task: " + firstTask);
        // Peeking top element from the stack
         Console.WriteLine("Peeking top element: " + taskQueue.Peek());

    }
}

Output:

Count the items in Queue is 4
First task: Task1
Peeking top element: Task2

When to Use Queues?

1. You need to process elements in the order they arrive (FIFO).

2. Tasks or jobs must be handled in the order they are received.

Example:

  1. Printer queues (first job to be sent is the first job printed).
  2. Task scheduling (process tasks as they come).
  3. Breadth-first search (BFS) in graphs.