Learn to program in Visual Basic .NET, the right way

Collections - Queue(Of T)

What are Queue(Of T)s?

Queue(Of T), which from this point forward I will refer to as "Queue" or "Queues", are dynamic collections used to store zero or more values that are the same data type.

Just like Lists and Dictionaries, Queues reside in the System.Collections.Generic namespace.

The T in Queue(Of T) refers to the data type that the collection will store.

FIFO

Queues represent a FIFO collection, this is to say that the first item that was added to the collection will be the first item to be removed.

The example used in the Stack lesson was a deck of cards. This is because the last card added to the deck would be the first card delt.

Think of a Queue like a line of customers. Customers will file in behind each other and it is a first-come-first-serve.

Class

Queues are just like Lists and Dictionaries in that they are a class. The following demonstrates how to initialize a Queue:

Fiddle: Live Demo

Add Values

There is one built-in methods of adding values to a Queue:

The Enqueue method will add one value to the top of the collection. The following demonstrates how to add a value to a Queue using the Enqueue method:

Fiddle: Live Demo

Remove Values

There is one built-in methods of removing values from a Queue:

The Dequeue method will remove and return the top-most value of the Queue. The following demonstrates how to remove a value from a Queue:

Fiddle: Live Demo

Exception

If you try to remove a Value, but the Queue is empty, then you will get a InvalidOperationException.

If you are unsure of if there are any items in the Queue, then use a conditional statement to check if Queue's Count property is not 0.