BlackWaspTM
.NET Framework
.NET 1.1+

The Queue Collection (2)

The fortieth part of the C# Fundamentals tutorial describes the use of the Queue class. This collection includes the functionality required in a 'First In, First Out' (FIFO) queuing structure. Queues allow items to be held in order for later processing.

Using Queue Functions

Enqueue Method

Queue structures allow new items to be added to the end of the queue and existing items to be extracted from the front. To add a new item to the end of the queue, the Enqueue method is called. The method has a single parameter containing the object to add to the queue.

Queue waiting = new Queue();

waiting.Enqueue("Mrs Brown");
waiting.Enqueue("Mr Green");
waiting.Enqueue("Miss Black");

Console.WriteLine("Count: {0}", waiting.Count);     // Outputs "Count: 3"

Dequeue Method

You can extract items from a queue with the Dequeue method. This returns the item that appears at the front of the queue as an object, which you may cast to the correct type. In the following example, the ToString method is used to perform the conversion as three items are added to and then extracted from a queue. Note that the order of extraction matches the order in which the items were added.

Queue waiting = new Queue();

waiting.Enqueue("Mrs Brown");
waiting.Enqueue("Mr Green");
waiting.Enqueue("Miss Black");

while (waiting.Count != 0)
{
    string next = waiting.Dequeue().ToString();
    Console.WriteLine(next);
}

/* OUTPUT

Mrs Brown
Mr Green
Miss Black

*/

Peek Method

You may wish to obtain the item at the front of the queue without modifying the collection's contents. The Peek method is similar to Dequeue but when the next item is retrieved, it also remains at the front of the queue.

Queue waiting = new Queue();

waiting.Enqueue("Mrs Brown");
waiting.Enqueue("Mr Green");
waiting.Enqueue("Miss Black");

string next = waiting.Peek().ToString();
Console.WriteLine(next);                            // Outputs "Mrs Brown"
Console.WriteLine("Count: {0}", waiting.Count);     // Outputs "Count: 3"
15 June 2007