Queue<T> · C#

Peek / TryPeek

Returns the front element without removing it.

public T Peek(); public bool TryPeek(out T result)

Complexity

Best caseO(1)
Worst caseO(1)
Extra spaceO(1)

One array read at the head index.

Tested example

var queue = new Queue<int>([7, 8]);
Assert.Equal(7, queue.Peek());     // reads the front, removes nothing
Assert.Equal(2, queue.Count);
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/QueueExamples.cs

Behaviour

Returns
The front element.
Errors and preconditions
Peek: InvalidOperationException if empty.
Changes
Nothing.
Memory and invalidation
No allocation.