C# | Queue.Enqueue() Method

In this post we will learn about C# | Queue.Enqueue() Method. When we create a queue and want to add element in it then this method come into picture. This method is used to add an object to the end of the “Queue” and it comes under the namespace named System.Collections.

In below code the parameter obj is the object which will get added to Queue using Enqueue method.

public virtual void Enqueue (object obj);

Enqueue method

Basic used of Enqueue () method is to add the element in the queue. Queue use FIFO principle means element which is added at first will be removed at first. We can remove the element using Dequeue () method. Dequeue () basically remove the last element available in the queue.

Dequeue method:

This method is used to remove element from the Queue, and it use FIFO principle to remove element. hence element added at first will get removed at first. Check out below example.

Clear method:

Clear method is used to clear all available elements in the queue. After executing this method, all elements will get removed and count in Queue will become Zero.

Let’s elaborate above methods more using one detailed example below.

public class CodeConfig
{
  static void Main(string[] args)
        {
            //Queue<Object> queue = new Queue<Object>();  // we can also use object or know data type too 
            Queue<string> queue = new Queue<string>();
            queue.Enqueue("A");
            queue.Enqueue("B");
            queue.Enqueue("C");
            queue.Enqueue("D");
            queue.Enqueue("E");
            queue.Enqueue("F");
            queue.Enqueue("G");
            queue.Enqueue("H");
            Console.Write("Count of elements = " + queue.Count +"\n");

            foreach (string i in queue)
            {
                Console.WriteLine(i);
            }
            queue.Dequeue();   //remove last element from current available elements, using FIFO. 
            queue.Dequeue();   //remove last element from current available elements, using FIFO. 
            Console.WriteLine("Queue...UPDATED\n");
            foreach (string i in queue)
            {
                Console.WriteLine(i);
            }
            Console.Write("Count of elements (updated) = " + queue.Count +"\n");
            queue.Clear();
            Console.Write("Count of elements (after clear) = " + queue.Count + "\n");
            Console.ReadLine();
        }   
}

Output will be:

Queue - https://codeconfig.in

In above example we add element from A to H and Dequeue () it 2 times. As we know Dequeue() will remove element so it will remove using FIFO so A and B get removed form Queue and total element we are left with is 6. Next, we use clear method on queue, and it will clear all available elements from the given Queue. Hence at last we only left with zero elements in our Queue.