Queue<T> · C#

Enqueue

Adds an element at the back.

public void Enqueue(T item)

Complexity

Best caseO(1)
AmortizedO(1)
Worst caseO(n) when the buffer is full
Extra spaceO(1) amortized

Write at the tail index and advance it modulo the capacity. A full buffer doubles and copies the elements in order, which amortizes to O(1).

Tested example

var queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
Assert.Equal(2, queue.Count);
Assert.Equal(["first", "second"], queue); // enumerates front to back
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/QueueExamples.cs

Parameters

item
The element.

Behaviour

Returns
Nothing.
Errors and preconditions
None.
Changes
Count increases by 1; may replace the buffer.
Memory and invalidation
Growth allocates a new array and unwraps the ring into it.