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.
In queues, we can add elements only at the back and retrieve elements only at the front. For instance, we would like to buy a ticket for a concert. If we go earlier, we are going to buy earlier a ticket. If we are late, we will have to go to the end of the queue and wait for everyone who has come earlier. This behavior is analogous to the objects in the ADT queue.
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:
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:
- Printer queues (first job to be sent is the first job printed).
- Task scheduling (process tasks as they come).
- Breadth-first search (BFS) in graphs.
C# Queue – Interview Questions
Q 1: What is Queue?
Q 2: Method to add item?
Q 3: Method to remove item?
Q 4: Can Queue store duplicate items?
Q 5: Which namespace contains Queue?
C# Queue – Objective Questions (MCQs)
Q1. Which method adds an element at the end of a queue?
Q2. Which method removes an element from the front of the queue?
Q3. What is the order of processing in a queue?
Q4. Which method returns the first element without removing it?
Q5. What happens if Dequeue() is called on an empty queue?