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>
.
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.
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
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
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()));}}