Summary
Represents a first-in, first-out (FIFO) collection of objects.
Remarks
A Queue
is a collection that is used for FIFO (first-in, first-out) operations. Objects are enqueued (added) to the end of the Queue
and dequeued (removed) from the beginning of the Queue
.
The Queue
class is not specific to a particular type of element. It can store any type of object. For a generic equivalent, see System.Collections.Generic.Queue<T>
.
The elements in the Queue
are stored in objects. This means that you can store any type of object, including null
references. The type of the elements is not restricted to that of a specific type.
The Queue
allows duplicate elements.
If the number of elements in the Queue
exceeds the capacity, the Queue
is automatically resized by reallocating memory.
The Queue
is not thread-safe. If you need thread-safe access to the Queue
, consider using the synchronized wrapper returned by Queue.Synchronized(Queue)
method.
Example
The following code example demonstrates how to use the Queue
class to create a queue, add elements, and remove elements.
using System;
using System.Collections;
public class Example
{
public static void Main()
{
// Create a Queue.
Queue myQueue = new Queue();
// Add elements to the queue.
myQueue.Enqueue("Hello");
myQueue.Enqueue("World");
myQueue.Enqueue(123);
myQueue.Enqueue(true);
// Display the number of elements in the queue.
Console.WriteLine("Count: {0}", myQueue.Count);
// Peek at the element at the beginning of the queue.
Console.WriteLine("Peek: {0}", myQueue.Peek());
// Remove and display elements from the queue.
Console.WriteLine("Dequeue: {0}", myQueue.Dequeue());
Console.WriteLine("Dequeue: {0}", myQueue.Dequeue());
// Display the remaining elements in the queue.
Console.WriteLine("Remaining elements:");
foreach (object obj in myQueue)
{
Console.WriteLine(obj);
}
// Clear the queue.
myQueue.Clear();
Console.WriteLine("Count after Clear: {0}", myQueue.Count);
}
}