Generic Queue

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
Exam Prep. Guides
Exam 70-536 Study Guide

1. Types and collections

2. Process, threading,…
3. Embedding features
4. Serialization, I/O
5. .NET Security
6. Interop., reflection,…
7. Global., drawing, text

edit

Contents

FIFO

The Queue class allows the implementation of a FIFO (First-In-First-Out) storage system.

Image:FIFO.gif

Due to Queue being a collection it can easily be simulated using a List. This is handy to remember so that if find yourself trying to implement such a system just remember that one already exists!

Generic.Queue vs Queue

The Collections.Generic.Queue should always be chosen over the Collections.Queue class to promote type safety. However, their basic operation is identical in every area apart from when using an enumerator.


Usage of Generic Queue

System.InvalidOperationException thrown if no check for within bounds.

byte data = 42;
Queue<byte> myQueue = new Queue<byte>();
 
myQueue.Enqueue(data);
 
if (myQueue.Count > 0) //Check within bounds
{
   data = myQueue.Dequeue();
}

Simulation of Queue using Generic List

Note that by simulating a queue like this means that all elements are open for access and therefore the queue can be abused.

System.ArgumentOutOfRangeException thrown if no check for within bounds

byte data = 42;
List<byte> myList = new List<byte>();
 
myList.Add(data); //Enqueue
        
if (myList.Count > 0) //Check within bounds
{
   //Dequeue
   data = myList[0];
   myList.RemoveAt(0);
}

Enumerator

The Enumerator or more precisely the Queue<T>.Enumerator allows simple iteration through the elements of the Queue.

Note: To protect the Queue from abuse the enumerator only allows read operations.

Unlike the IEnumerator (returned by Collections.Queue) the Queue<T>.Enumerator does not provide a Reset method.

The most important thing to remember when using an enumerator is not to modify the Queue once an instance of the enumerator has been created. Therefore the fool-proof way of ensuring this is to stick it inside its own method.


using System;
using System.Collections.Generic;
 
static void queueEnumeratorEG()
{
  Queue<byte> myQueue = new Queue<byte>();
 
  myQueue.Enqueue(1);
  myQueue.Enqueue(2);
  myQueue.Enqueue(3);
  myQueue.Enqueue(4);
 
  queuePrint(myQueue);
  
  myQueue.Dequeue();
  myQueue.Dequeue();
 
  queuePrint(myQueue);
}
 
static void queuePrint(Queue<byte> myQueue)
{
  Queue<byte>.Enumerator mqEnumerator = myQueue.GetEnumerator();
 
  while (mqEnumerator.MoveNext())
  {
    Console.WriteLine(mqEnumerator.Current.ToString());
  }
  Console.WriteLine();
}

The alternative is to use a foreach statement which uses the enumerator behind the scenes.

MSDN Documentation


Personal tools