Open In App

C# Queue with Examples

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A Queue in C# is a collection that follows the First-In-First-Out (FIFO) principle which means elements are processed in the same order they are added. It is a part of the System.Collections namespace for non-generic queues and System.Collections.Generic namespace for generic queues.

Key Features:

  • FIFO Behavior: The first element added is the first to be removed.
  • Dynamic Size: A queue can grow or shrink as needed.
  • Thread Safety: The Queue class is not thread-safe by default. Use ConcurrentQueue for thread-safe operations.
  • Common Operations:
    • Enqueue: Add an element to the queue.
    • Dequeue: Remove and return the first element.
    • Peek: View the first element without removing it.
    • Contains: Check if an element exists in the queue.
CSharp-Queue

Example: This example demonstrates how to use a Queue in C# by enqueueing elements and then dequeuing them in FIFO (First-in-first-out ) order.

C#
// C# program to demonstrates how to use Queue
using System;
using System.Collections.Generic;

class Geeks {
    public static void Main(string[] args)
    {
        // Create a new queue
        Queue<int> q = new Queue<int>();

        // Enqueue elements into the queue
        q.Enqueue(1);
        q.Enqueue(2);
        q.Enqueue(3);
        q.Enqueue(4);

        // Dequeue elements from the queue
        while (q.Count > 0) {
            Console.WriteLine(q.Dequeue());
        }
    }
}

Output
1
2
3
4

Hierarchy of Queue Class

CSharp-Queue-Hierarchy
  • The Queue class implements the IEnumerable, ICollection, and ICloneable interfaces.
  • When we add an item in the list, it is called enqueue.
  • When we remove an item, it is called dequeue.
  • Queue accepts null as a valid value for reference types.
  • As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array.
  • In Queue, we are allowed to store duplicate elements.
  • The capacity of a Queue is the number of elements the Queue can hold.

Creating a Queue

Queue class has four constructors which are used to create the queue which are as follows:

  • Queue(): This constructor is used to create an instance of the Queue class which is empty and having the default initial capacity, and uses the default growth factor.
  • Queue(ICollection): This constructor is used to create an instance of Queue class which contains elements copied from the specified collection, has the same initial capacity as the number of elements copied, and uses the default growth factor.
  • Queue(Int32): This constructor is used to create an instance of the Queue class which is empty and having specified initial capacity, and uses the default growth factor.
  • Queue(Int32, Single): This constructor is used to create an instance of Queue class which is empty and having specified initial capacity, and uses the specified growth factor.

Let’s see how to create an Queue using Queue() constructor:

Step 1: Include System.Collections namespace in your program with the help of using keyword

using System.Collections;

Step 2: Create a Stack using Stack class

Queue q = new Queue();

Performing Various Operations on Queue

1. Adding Elements:  We use Enqueue() method to insert elements in a Queue.

Example: This example demonstrates how to create a queue in C# and add various elements to it using the Enqueue() method, then access and display the elements using a foreach loop.

C#
// C# program to demonstrate how to
// create and add elements into a queue
using System;
using System.Collections;

class Geeks {

    public static void Main()
    {
        // Create a queue
        // Using Queue class
        Queue q = new Queue();

        // Adding elements to the Queue
        // Using Enqueue method
        q.Enqueue("Geeks");
        q.Enqueue("geeksforgeeks");
        q.Enqueue(null);
        q.Enqueue(1);
        q.Enqueue(10.0);

        // Accessing the elements
        // of q Queue
        // Using foreach loop
        foreach(var e in q) { 
          Console.WriteLine(e); 
        }
    }
}

Output
Geeks
geeksforgeeks

1
10

2. Remove Elements: The Queue class provides two different methods to remove elements and the methods are:

  • Clear() Method: The Clear()is used to remove the objects from the queue.
  • Dequeue() Method: The Dequeue() removes the beginning element of the queue.

Example: This example displays the contents of the Queue before and after removal.

C#
// C# Program to remove
//  elements from a queue
using System;
using System.Collections.Generic;

class Geeks {
    public static void Main(string[] args)
    {
        // Initialize a queue
        Queue<string> q = new Queue<string>();

        // Inserting elements into the 
        // queue using Enqueue()
        q.Enqueue("Geeks");
        q.Enqueue("For");
        q.Enqueue("Geeks");
        q.Enqueue("For");

        // Initial queue
        Console.WriteLine("Initial queue: ");
        foreach(var item in q) { 
          Console.WriteLine(item); 
        }

        // Removing the front element
        q.Dequeue();

        // Final queue after removal
        Console.WriteLine("\nUpdated queue after Dequeue:");
        foreach(var item in q) { 
          Console.WriteLine(item); 
        }
    }
}

Output
Initial queue: 
Geeks
For
Geeks
For

Updated queue after Dequeue:
For
Geeks
For

3. Get the Topmost Element of the Queue: The Queue class provides two different methods to find the topmost element of the Queue and the methods are listed below:

  • Peek() Method: The Peek() method returns the object at the beginning of the Queue without removing it.
  • Dequeue() Method: The Dequeue() method returns the object at the beginning of the Queue with modification means this method remove the topmost element of the queue.

Example: This example demonstrates how to peek at the topmost element of a Queue.

C#
// C# Program to get the
// front element of the Queue
using System;
using System.Collections.Generic;

class Geeks {
    public static void Main(string[] args)
    {
        // Create a new queue of integers
        Queue<int> q = new Queue<int>();

        // Enqueue elements into the queue
        q.Enqueue(10);
        q.Enqueue(20);
        q.Enqueue(30);

        // Checking if the queue is not empty before
        // accessing the front element
        if (q.Count > 0) {

            // Peek() returns the frontmost element without
            // removing it
            int f = q.Peek();
            Console.WriteLine(
                "The frontmost element in the queue is: "
                + f);
        }
        else {
            Console.WriteLine("The queue is empty.");
        }
    }
}

Output
The frontmost element in the queue is: 10

4. Check the Availability of Elements in the Queue: Queue class provide Contains() method to check if the element is present in the Queue or not.

Example: This program demonstrates how to check if the specified element are present in a Queue using the contains() method.

C#
// C# Program to check the
// availability of elements in the queue
using System;
using System.Collections.Generic;

class Geeks {
    public static void Main(string[] args)
    {
        // Create a new queue of integers
        Queue<int> q = new Queue<int>();

        // Enqueue elements into the queue
        q.Enqueue(10);
        q.Enqueue(20);
        q.Enqueue(30);

        // Check if the element 20 is present in the queue
        Console.WriteLine(
            "The element 20 is present in the queue: "
            + q.Contains(20));

        Console.WriteLine(
            "The element 100 is present in the queue: "
            + q.Contains(100));
    }
}

Output
The element 20 is present in the queue: True
The element 100 is present in the queue: False

Generic Stack vs Non-Generic Queue

Generic QueueNon-Generic Queue
Generic queue is defined under System.Collections.Generic namespace.Non-Generic queue is defined under System.Collections namespace.
Generic queue can only store same type of elements.Non-Generic queue can store same type or different types of elements.
There is a need to define the type of the elements in the queue.There is no need to define the type of the elements in the queue.
It is type- safe.It is not type-safe.


Next Article
Article Tags :

Similar Reads