Non-Generic Queue in C#

Non-Generic Queue Collection Class in C# with Examples

In this article, I am going to discuss the Non-Generic Queue Collection Class in C# with Examples. Please read our previous article where we discussed the Non-Generic Stack Collection Class in C# with Examples. The Non-Generic Queue Collection Class in C# represents a first-in, first-out collection of objects. That means we need to use this collection when we need first-in, first-out access to items. At the end of this article, you will understand the following pointers.

  1. What is a Queue in C#?
  2. Methods, Properties, and Constructor of Non-Generic Queue Collection Class in C#
  3. How to create a Queue in C#?
  4. How to Add Elements into a Queue in C#?
  5. How to Remove Elements from the Queue in C#?
  6. How to get the first element of the queue in C#?
  7. How to check whether an element exists or not in the Queue in C#?
  8. How to Clone the Non-Generic Queue Collection in C#?
  9. How to copy a queue to an existing array in C#?
  10. When to Use Non-Generic Queue Collection in C#?
What is a Queue in C#?

The Non-Generic Queue Collection Class in C# works in the FIFO(First In First Out) principle. So, we need to use the Non-Generic Queue Collection class in C#, when we need First in First out access to the items of a collection. That means the item which is added first will be removed first from the collection. When we add an item into the queue, then it is called enqueuing an item. Similarly, when we remove an item from the queue then it is called dequeuing an item. The Queue Collection class belongs to the System.Collections namespace and implements ICollection, IEnumerable, and ICloneable interfaces.

Let us understand the FIFO principle with an example. Imagine a queue of people waiting for a ticket in a cinema hall. Normally, the first person who enters the queue will be the first person to get the ticket from the counter. Similarly, the last person who enters the queue will be the last person to get the ticket from the counter.

Note: Queue is defined as both generic and non-generic types of collection. Generic Queue is defined in System.Collections.Generic namespace whereas non-generic Queue is defined under System.Collections namespace. Here in this article, we will discuss the Non-Generic Queue Collection Class in C# with Examples.

Characteristics of Non-Generic Queue Collection Class in C#:
  1. Enqueue adds an element to the end of the Queue.
  2. Dequeue removes the oldest element from the start of the Queue.
  3. Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue.
  4. The capacity of a Queue is the number of elements the queue can hold. As we add elements to a queue, the capacity of the queue is automatically increased.
  5. The Non-Generic Queue Collection in C# allows both null and duplicate values.
Methods, Properties, and Constructor of Non-Generic Queue Collection Class in C#:

If you go to the definition of Queue class, then you will see the following. Here, you can see that the non-generic queue collection class implements the IEnumerable, ICollection, and ICloneable interfaces.

Methods, Properties, and Constructor of Non-Generic Queue Collection Class in C#

How to create a Queue in C#?

The non-generic Queue collection class in C# has provided four constructors which we can use to create a queue. The constructors are as follows:

  1. Queue(): It is used to initialize a new instance of the Queue class that is empty and has the default initial capacity, and uses the default growth factor.
  2. Queue(ICollection col): It is used to initialize a new instance of the Queue class that contains elements copied from the specified collection and has the same initial capacity as the number of elements copied and uses the default growth factor. Here, the parameters col specifies the System.Collections.ICollection to copy elements from.
  3. Queue(int capacity): It is used to initialize a new instance of the Queue class that is empty, has the specified initial capacity, and uses the default growth factor. Here, the parameter capacity specifies the initial number of elements that the Queue can contain.
  4. Queue(int capacity, float growFactor): It is used to initialize a new instance of the Queue class that is empty, has the specified initial capacity, and uses the specified growth factor. Here, the parameter capacity specifies the initial number of elements that the Queue can contain and the parameter growFactor specifies the factor by which the capacity of the Queue is expanded.

Let’s see how to create a queue using the Queue() constructor in C#:
Step1:
As the Queue collection class belongs to System.Collections namespace, so first, we need to include System.Collections namespace in our program with the help of “using” keyword as follows:
using System.Collections;

Step2:
Next, we need to create an instance of the Queue class using the Queue() constructor as follows:
Queue queue = new Queue();

How to Add Elements into a Queue in C#?

If we want to add elements to a queue, then we need to use the Enqueue() method of the Queue class.

  1. Enqueue(object obj): This method is used to add an object to the end of the Queue. Here, the parameter obj specifies the object to add to the Queue. The value can be null
Example to Understand How to Create a Queue and Add Elements in C#:

For a better understanding of how to create a queue and how to add elements to a queue in C#, please have a look at the below example.

using System;
using System.Collections;

namespace QueueCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a queue collection
            Queue queue = new Queue();

            //Adding item to the queue using the Enqueue method
            queue.Enqueue(101);
            queue.Enqueue("Hello");
            queue.Enqueue(3.14f);
            queue.Enqueue(true);
            queue.Enqueue(67.8);
            queue.Enqueue('A');

            //Printing the queue items using foreach loop
            foreach (var item in queue)
            {
                Console.WriteLine(item);
            }
            
            Console.ReadKey();
        }
    }
}
Output:

Example to Understand How to Create a Queue and Add Elements in C#

How to Remove Elements from the Queue in C#?

In Queue, you are allowed to remove elements from the beginning of the Queue. If you want to remove elements from the queue, then you need to use the following two methods provided by the Non-Generic Collection Queue class.

  1. Dequeue(): This method is used to remove and return the object at the beginning of the Queue. It returns the object that is removed from the beginning of the Queue.
  2. Clear(): This method is used to remove all objects from the queue.

Let us see an example to understand the Dequeue() and Clear() method of Queue Class in C#. Please have a look at the below example.

using System;
using System.Collections;

namespace QueueCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a queue collection
            Queue queue = new Queue();

            //Adding item to the queue using the Enqueue method
            queue.Enqueue(101);
            queue.Enqueue("Hello");
            queue.Enqueue(3.14f);
            queue.Enqueue(true);
            queue.Enqueue(67.8);
            queue.Enqueue('A');

            //Printing the queue items using foreach loop
            Console.WriteLine($"All Queue Elements: Count {queue.Count}");
            foreach (var item in queue)
            {
                Console.Write($"{item} ");
            }

            //Removing and Returning an item from the queue using the Dequeue method
            Console.WriteLine($"\n\nDeleted Element: {queue.Dequeue()}");

            //Printing item after removing the first added item
            Console.WriteLine($"\nAll Queue Elements After Deletion: Count {queue.Count}");
            foreach (var item in queue)
            {
                Console.Write($"{item} ");
            }

            //Printing Items After Clearing the Queue
            queue.Clear();
            Console.WriteLine($"\n\nQueue Elements After Clear Operation: Count {queue.Count}");
            foreach (var item in queue)
            {
                Console.Write($"{item} ");
            }
            Console.ReadKey();
        }
    }
}
Output:

How to Remove Elements from the Queue in C#

How to get the first element of the queue in C#?

The Non-Generic Queue Collection class in C# provides the following two methods to get the first element of the queue collection

  1. Dequeue(): The Dequeue() method of the Queue class is used to Remove and return the object from the beginning of the Queue. If there is no object (or element) present in the Queue and if we are trying to remove an item or object from the Queue using the pop() method then it will throw an exception i.e. System.InvalidOperationException
  2. Peek(): The peek() method of the Queue class is used to return the oldest object i.e. the object present at the start of the Queue without removing it. If there is no object (or element) present in the Queue and if we are trying to return an item (object) from the Queue using the peek() method then it will throw an exception i.e. System.InvalidOperationException

For a better understanding, please have a look at the below example which shows how to get the first element from the queue.

using System;
using System.Collections;

namespace QueueCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a Queue collection
            Queue queue = new Queue();

            //Adding item to the queue using the Enqueue method
            queue.Enqueue(101);
            queue.Enqueue("Hello");
            queue.Enqueue(3.14f);
            queue.Enqueue(true);
            queue.Enqueue(67.8);
            queue.Enqueue('A');

            Console.WriteLine($"Total Elements present in Queue : {queue.Count}");

            // Fetch First Element of Queue Using Dequeue method
            Console.WriteLine($"First Element of Queue is {queue.Dequeue()}");
            Console.WriteLine($"Total Elements present in Queue : {queue.Count}");

            // Fetch the topmost element from Queue Using Peek method
            Console.WriteLine($"First Element of Queue is {queue.Peek()}");
            Console.WriteLine($"Total Elements present in Queue : {queue.Count}");
            Console.ReadKey();
        }
    }
}
Output:

How to get the first element of the queue in C#

Note: If you want to remove and return the first element from the queue, then use the Dequeue method and if you only want to return the first element from the queue without removing it, then use the Peek method and this is the only difference between these two methods of Queue Collection class in C#.

How to check whether an element exists or not in the Queue in C#?

If you want to check whether an element exists or not in the queue, then you need to use the following Contains() method of the Queue Collection Class in C#. You can also use this Contains() method to search for an element in the given queue.

  1. Contains(object obj): This method is used to determine whether an element is in the Queue. Here, the parameter obj specifies the object or element to locate in the Queue. The value can be null. It returns true if obj is found in the queue; otherwise, false.

Let us understand this with an example. The following example shows how to use the Contains() method of the Queue class in C#.

using System;
using System.Collections;

namespace QueueCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a Queue collection
            Queue queue = new Queue();

            //Adding item to the queue using the Enqueue method
            queue.Enqueue(101);
            queue.Enqueue("Hello");
            queue.Enqueue(3.14f);
            queue.Enqueue(true);
            queue.Enqueue(67.8);
            queue.Enqueue('A');

            Console.WriteLine("All Elements of Queue");
            foreach (var item in queue)
            {
                Console.Write($"{item} ");
            }

            Console.WriteLine("\nChecking if the element Hello is present in the queue or not");
            // Checking if the element Hello is present in the Stack or not

            if (queue.Contains("Hello") == true)
            {
                Console.WriteLine("Element Hello is found");
            }
            else
            {
                Console.WriteLine("Element Hello is not found");
            }
            Console.ReadKey();
        }
    }
}
Output:

How to check whether an element exists or not in the Queue in C#

Note: The Contains(object obj) method of Non-Generic Collection Queue Class in C# takes O(n) time to check if the element exists in the queue. This should be taken into consideration while using this method.

How to Clone the Non-Generic Queue Collection in C#?

If you want to clone the Non-Generic Queue collection in C#, then you need to use the following Clone() method provided by the Queue Collection Class.

  1. Clone(): This method is used to create and return a shallow copy of a Queue object.

For a better understanding, please have a look at the below example.

using System;
using System.Collections;

namespace QueueCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a queue collection
            Queue queue = new Queue();

            //Adding item to the queue using the Enqueue method
            queue.Enqueue(101);
            queue.Enqueue("Hello");
            queue.Enqueue(3.14f);
            queue.Enqueue(true);
            queue.Enqueue(67.8);

            //Printing All Queue Elements using For Each Loop
            Console.WriteLine("Queue Elements:");
            foreach (var item in queue)
            {
                Console.WriteLine(item);
            }

            //Creating a clone queue using Clone method
            Queue cloneQueue = (Queue)queue.Clone();
            Console.WriteLine("\nCloned Queue Elements:");
            foreach (var item in cloneQueue)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}
Output:

How to Clone the Non-Generic Queue Collection in C#

How to copy a queue to an existing array in C#?

In order to copy a queue to an existing array in C#, we need to use the following CopyTo method of the Non-Generic Queue Collection Class.

  1. CopyTo(Array array, int index): The CopyTo method of Non-Generic Queue Collection Class in C# is used to copy the System.Collections.Queue elements to an existing one-dimensional System.Array, starting at the specified array index. Here, the parameter array specifies the one-dimensional Array that is the destination of the elements copied from Queue. The Array must have zero-based indexing. The index parameter specifies the zero-based index in the array at which copying begins. If the parameter array is null, then it will throw ArgumentNullException. If the parameter index is less than zero, then it will throw ArgumentOutOfRangeException.

This method works on one-dimensional arrays and does not change the state of the queue. The elements are ordered in the array in the same way as the order of the elements from the start of the queue to the end. Let us see an example for a better understanding.

using System;
using System.Collections;

namespace QueueCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a queue collection
            Queue queue = new Queue();

            //Adding item to the queue using the Enqueue method
            queue.Enqueue(101);
            queue.Enqueue("Hello");
            queue.Enqueue(3.14f);
            queue.Enqueue(true);
            queue.Enqueue(67.8);

            //Printing All Queue Elements using For Each Loop
            Console.WriteLine("Queue Elements:");
            foreach (var item in queue)
            {
                Console.WriteLine(item);
            }

            //Copying the queue to an object array
            object[] queueCopy = new object[5];
            queue.CopyTo(queueCopy, 0);
            Console.WriteLine("\nQueue Copy Array Elements:");
            foreach (var item in queueCopy)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}
Output:

How to copy a queue to an existing array in C#

Properties of Queue Class in C#
  1. Count: It gets the number of elements contained in the Queue.
  2. IsSynchronized: It gets a value indicating whether access to the Queue is synchronized (thread-safe). It returns true if access to the queue is synchronized (thread-safe); otherwise, false. The default is false.
  3. SyncRoot: It gets an object that can be used to synchronize access to the Queue. It returns an object that can be used to synchronize access to the queue.
Non-Generic Queue Collection Class in C# Overview

The following are some important points that you need to remember while working with Queue.

  1. In c#, queues are used to store a collection of objects in a FIFO (First in, First out) style, i.e., the element which added first will remove first.
  2. By using Enqueue() method, we can add elements at the end of the queue.
  3. The Dequeue() method will remove and return the first element from the queue.
  4. The queue Peek() method will always return the first element of the queue, and it won’t delete elements from the queue.
When to Use Non-Generic Queue Collection in C#?

This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other. It is not recommended to use the Queue class for new development. Instead, it is recommended to use the generic Queue<T> Collection class.

A Queue is useful when we need temporary storage for information; that is when we might want to discard an element after retrieving its value. Use Queue if you need to access the information in the same order that it is stored in the collection. Use ConcurrentQueue<T> if you need to access the collection from multiple threads concurrently.

In the next article, I am going to discuss the Non-Generic SortedList Collection Class in C# with Examples. Here, in this article, I try to explain the Non-Generic Collection Queue Class in C# with Examples. I hope this Non-Generic Queue Collection Class in C# with Examples article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

4 thoughts on “Non-Generic Queue in C#”

  1. blank
    Loknadh.Ravineni

    Hi Typing Error under the section Methods of Queue class in C# Here the method name should be Peek() but it was typed as Peep()

  2. blank
    Mohamed Hesham

    You used the term stack instead of queue in dequeue and enqueue several times. Is it intended or is it just a typo?

Leave a Reply

Your email address will not be published.