Open In App

C# Queue Class

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

In C#, the Queue<T> class is the part of the System.Collections.Generic namespace and represent a first-in-first-out (FIFO) collection of objects. When we add an item to the list, it is called enqueue, and when we remove an item, it is called dequeue.

  • Enqueue adds an element to the end of the Queue.
  • Dequeue removes the oldest element from the start of the Queue.
  • Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue.
  • The capacity of a Queue is the number of elements the Queue can hold.
  • As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array.
  • Queue accepts null as a valid value for reference types and allows duplicate elements.

Example: This example, demonstrates how to create a queue, add different elements to it using the enqueue() Method, and then display the elements using for-each loop.

C#
// C# program to demonstrates the working of queue
using System;
using System.Collections;

public class Geeks {
    static public void Main()
    {

        // Create a queue
        // Using Queue class
        Queue q = new Queue();

        // Adding elements in Queue
        // Using Enqueue() method
        q.Enqueue("GFG");
        q.Enqueue(1);
        q.Enqueue(10);
        q.Enqueue(null);
        q.Enqueue(2.4);
        q.Enqueue("Geeks123");

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

Output
GFG
1
10

2.4
Geeks123

Declaration of Queue Class

In C#, the Queue<T> is a generic collection, meaning it can hold elements of a specific type. T is the type of elements the queue will hold

Queue<T> q = new Queue<T>();

Constructors

The Queue<T> class provides four constructor which are listed below in the table:

Constructor

Description

Queue()

Initializes a new instance of the Queue class that is empty, has the default initial capacity, and uses the default growth factor.

Queue(ICollection)

Initializes a new instance of the Queue class that 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)

Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the default growth factor.

Queue(Int32,Single)

 Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the specified growth factor

Example: This example demonstrates the total number of elements present in the queue.

C#
// C# program to count the number 
// of elements present in the queue
using System;
using System.Collections;

class Geeks {

    public static void Main()
    {

        // Creating a Queue
        Queue q = new Queue();

        // Inserting the elements into the Queue
        q.Enqueue("one");
        q.Enqueue("two");
        q.Enqueue("three");
        q.Enqueue("four");
        q.Enqueue("five");

        // Displaying the count of elements
        // contained in the Queue
        Console.Write(
            "Total number of elements in the Queue are : ");

        Console.WriteLine(q.Count);
    }
}

Output
Total number of elements in the Queue are : 5

Properties

The Queue<T> class provides several properties to access its state.

PropertyDescription
CountGets the number of elements contained in the Queue.
IsSynchronizedGets a value indicating whether access to the Queue is synchronized (thread safe).
SyncRootGets an object that can be used to synchronize access to the Queue.

Example: This example demonstrates how to use the SyncRoot property of a Queue to ensure thread safety.

C#
// C# program to illustrate the
// use of SyncRoot property of
// the Queue
using System;
using System.Threading;
using System.Collections;

namespace sync_root {

class Geeks {

    // Main Method
    static void Main(string[] args)
    {

        // Declaring an Queue
        Queue q = new Queue();

        // Adding elements to Queue
        q.Enqueue(1);
        q.Enqueue(2);
        q.Enqueue(3);
        q.Enqueue(4);
        q.Enqueue(5);

        // Using the SyncRoot property
        lock(q.SyncRoot)
        {
            // foreach loop to display
            // the elements in q1
            foreach(Object i in q) Console.WriteLine(i);
        }
    }
}
}

Output
1
2
3
4
5

Methods

MethodDescription
Clear()Removes all objects from the Queue.
Clone()Creates a shallow copy of the Queue.
Contains(Object)Determines whether an element is in the Queue.
CopyTo(Array, Int32)Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index.
Dequeue()Removes and returns the object at the beginning of the Queue.
Enqueue(Object)Adds an object to the end of the Queue.
Equals(Object)Determines whether the specified object is equal to the current object.
GetEnumerator()Returns an enumerator that iterates through the Queue.
GetHashCode()Serves as the default hash function.
GetType()Gets the Type of the current instance.
MemberwiseClone()Creates a shallow copy of the current Object.
Peek()Returns the object at the beginning of the Queue without removing it.
Synchronized(Queue)Returns a new Queue that wraps the original queue, and is thread safe.
ToArray()Copies the Queue elements to a new array.
ToString()Returns a string that represents the current object.
TrimToSize()Sets the capacity to the actual number of elements in the Queue.

Example: This example demonstrates that the specific element is present in the Queue using the Contains() method.

C#
// C# Program to check if the specified 
// element is present in the queue or not 
using System;
using System.Collections;

class Geeks {

    public static void Main()
    {

        // Creating a Queue
        Queue q = new Queue();

        // Inserting the elements into the Queue
        q.Enqueue(5);
        q.Enqueue(10);
        q.Enqueue(15);
        q.Enqueue(20);
        q.Enqueue(25);

        // Checking whether the element is
        // present in the Queue or not
        Console.WriteLine("The queue contains 7 ? :"
                          + q.Contains(7));
        Console.WriteLine("The queue contains 10 ? :"
                          + q.Contains(10));
    }
}

Output
The queue contains 7 ? :False
The queue contains 10 ? :True

Example: This example demonstrates how to convert a Queue to an object array using ToArray() method.

C#
// C# Program to Convert Queue to array
using System;
using System.Collections;

class Geeks {

    public static void Main()
    {

        // Creating a Queue  
        Queue q = new Queue();

        // Inserting the elements into the Queue 
        q.Enqueue("Geeks");
        q.Enqueue("for");
        q.Enqueue("Geeks");

        // Converting the Queue 
        // into object array 
        Object[] arr = q.ToArray();

        // Displaying the elements in array 
        foreach(Object i in arr)
        {
            Console.WriteLine(i);
        }
    }
}

Output
Geeks
for
Geeks


Similar Reads