Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
queue
enqueue
communitycreator

How to enqueue an element to a queue in C#

Surabhi Sharma

The Queue<T> generic class in the System.Collections.Generic namespace provides the Enqueue() method, which is used to insert an element at the end of the Queue<T>.

Syntax

public void Enqueue (T item);

This method takes the object to add to the Queue<T> as input. For reference types, this value can be null.

Things to note

  • The Queue<T> is backed internally by a circular array. If the count of elements in the queue is equal to the capacity, the capacity of the Queue<T> is increased by automatically reallocating the internal array. First, the existing elements of the queue are copied to the new array, and then the new element is added.

  • This method is an O(1) operation if the count of elements is less than the capacity.

  • This method becomes an O(n) operationwhere n is the count of elements when the count of elements is equal to the capacity as it needs to reallocate the new array to make space for the new element.

In this example, we have created a queue of strings and enqueued January and February strings to it.

We then print the queue elements. We add some more elements to the queue (March, April, May and June). Notice that it is added to the end of the queue, as Queue is a FIFOFirst In First Out data structure.

The program prints the below output and exits.

using System;
using System.Collections.Generic;

class QueueTest
{
    static void Main()
    {
        Queue<string> months = new Queue<string>();
        months.Enqueue("January");
        months.Enqueue("February");
        Console.WriteLine("Enqueued elements to the Queue \nQueue Items : {0}", string.Join(",", months.ToArray()));
        months.Enqueue("March");
        months.Enqueue("April");
        months.Enqueue("May");
        months.Enqueue("June");

        Console.WriteLine("Enqueued some more elements to the Queue \nQueue Items : {0}", string.Join(",", months.ToArray()));
       
    }
}

RELATED TAGS

c#
queue
enqueue
communitycreator
RELATED COURSES

View all Courses

Keep Exploring