C# Queue with Examples

In c#, Queue is used to represent a collection of objects which stores an elements in FIFO (First in, First out) style i.e. the element which added first will come out first. In queue, elements are inserted from one end and removed from another end.

 

Generally, queues are useful when we want to access an elements from the collection in same order that is stored and we can store a multiple null and duplicate values in queue based on our requirements.

 

By using Enqueue() and Dequeue() methods, we can add or delete an elements from the queue. Here, the Enqueue() method is useful to add an elements at the end of queue and the Dequeue() method is useful to remove an elements start from the queue.

 

Following is the pictorial representation of queue process flow in c# programming language.

 

C# Queue Process Flow Diagram

C# Queue Declaration

Generally, c# will support both generic and non-generic type of queues. Here, we will learn about non-generic queue collections by using System.Collections namespace.

 

As discussed, collection is a class so to define a queue, we must need to declare an instance of the queue class before we perform any operations like add, delete, etc. like as shown below.

 

Queue que = new Queue();

If you observe above queue declaration, we created a new queue (que) with an instance of queue class without specifying any size.

C# Queue Properties

Following are the some of commonly used properties of queue in c# programming language.

 

PropertyDescription
Count It will return the total number of elements in queue
IsSynchronized It is used to get a value to inidicate that an access to queue is synchronized (thread safe) or not.

C# Queue Methods

Following are the some of commonly used methods of queue to perform an operations like add, delete, etc. on elements of queue in c# programming language.

 

MethodDescription
Enqueue It is used to add an elements at the end of queue.
Dequeue It will remove and returns an item from the starting of queue.
Clear It will remove all the elements from queue.
Clone It will create a shallow copy of queue.
Contains It is used determine whether an element exists in queue or not.
Peek It is used to get a first element from the queue.
TrimToSize It is used set the capacity of queue to actual number of elements in the queue.

C# Queue Example

Here, we are going to use non-generic type of queue so we can add an elements of different data types to the queue using Enqueue() method. Following is the example of adding and accessing an elements of the queue in c#.

 

using System;

using System.Collections;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create and initialize a queue

            Queue que = new Queue();

            que.Enqueue("Welcome");

            que.Enqueue("Tutlane");

            que.Enqueue(20.5f);

            que.Enqueue(10);

            que.Enqueue(100);

            Console.WriteLine("******Queue Example******");

            Console.WriteLine("Number of Elements in Queue: {0}", que.Count);

            Console.WriteLine("******Queue Elements******");

            // Access Queue Elements 

            foreach (var item in que)

            {

                Console.WriteLine(item);

            }

            Console.ReadLine();

        }

    }

}

If you observe above example, we created a new queue (que) and added a different data type elements to the queue (que) using Enqueue() method and we used a foreach loop to iterate through a queue to get an elements from it.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Queue Example Result

 

If you observe above result, we got an elements from the queue in same order which we added first.

C# Dequeue() Method to Access Queue Elements

As discussed, the queue Dequeue() method will always remove and return a first element of the queue. Following is the example of accessing a queue elements using Dequeue() method in c#.

 

using System;

using System.Collections;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create and initialize a queue

            Queue que = new Queue();

            que.Enqueue("Welcome");

            que.Enqueue("Tutlane");

            que.Enqueue(20.5f);

            que.Enqueue(10);

            que.Enqueue(100);

            Console.WriteLine("Number of Elements in Queue: {0}", que.Count);

            Console.WriteLine("******Queue Elements******");

            // Access Queue Elements

            while (que.Count > 0)

            {

                Console.WriteLine(que.Dequeue());

            }

            Console.WriteLine("Number of Elements in Queue: {0}", que.Count);

            Console.ReadLine();

        }

    }

}

If you observe above example, we are accessing a queue elements by using Dequeue() method and calling a Dequeue method on empty queue will throw an exception (InvalidOperation) so to avoid that situation we are checking whether the count of queue elements greater than zero or not using while loop.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Queue Dequeue() Method to Access Elements Example Result

 

If you observe above result, every time the Dequeue() method has removed and returned a first element of the queue that’s the reason at the end we got a count of queue elements as 0.

 

In case, if you want to remove all the elements of queue, then you need to use clear() method.

C# Peek() Method to Access Queue Elements

As discussed, the queue Peek() method will always return a first element of the queue. Following is the example of accessing a queue elements using Peek() method in c#.

 

using System;

using System.Collections;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create and initialize a queue

            Queue que = new Queue();

            que.Enqueue("Welcome");

            que.Enqueue("Tutlane");

            que.Enqueue(20.5f);

            que.Enqueue(10);

            Console.WriteLine("Number of Elements in Queue: {0}", que.Count);

            Console.WriteLine("******Queue Elements******");

            // Access Queue Elements

            Console.WriteLine(que.Peek());

            Console.WriteLine(que.Peek());

            Console.WriteLine(que.Peek());

            Console.WriteLine("Number of Elements in Queue: {0}", que.Count);

            Console.ReadLine();

        }

    }

}

If you observe above example, we are accessing a queue elements by using Peek() method.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Queue Peek Method to Access Elements Example Result

 

If you observe above result, every time the Peek() method has returned a first element of the queue without removing any element that’s the reason at the end also the queue elements count is same as starting of the queue.

C# Queue Contains() Method

In c#, by using queue Contains() method we can check whether an element exists in queue or not. In case, if the element found in queue, then it will return true otherwise false.

 

Following is the example of using queue Contains() method to check whether an item exists in queue or not in c#.

 

using System;

using System.Collections;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create and initialize a queue

            Queue que = new Queue();

            que.Enqueue("Welcome");

            que.Enqueue("Tutlane");

            que.Enqueue(20.5f);

            que.Enqueue(10);

            que.Enqueue(100);

            Console.WriteLine("******Queue Example******");

            Console.WriteLine("Contains Element 4: {0}", que.Contains(4));

            Console.WriteLine("Contains Element 100: {0}", que.Contains(100));

            Console.WriteLine("Contains Key 'Hello': {0}", que.Contains("Hello"));

            Console.ReadLine();

        }

    }

}

If you observe above example, we used a Contains() method to check for a particular elements exists in queue (que) or not.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Queue Contains Method Example Result

C# Queue Overview

Following are important points which needs to remember about queue in c#.

 

  • 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 come out first.
  • By using Enqueue() method, we can add an elements at the end of queue.
  • The Dequeue() method will remove and return an oldest (first) element from the queue.
  • The queue Peek() method will always return a first element of the queue and it won’t delete any element from the queue.
 

PREVIOUS

C# HashTable