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

Collections - Stack(Of T)

What are Stack(Of T)s?

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

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

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

LIFO

Stacks represent a LIFO collection, this is to say that the last item that was added to the collection will be the first item to be removed.

The example used in the array lesson was the English alphabet. This is because in the alphabet, there are only 26 letters.

The example used in the List lesson was a garage. This is because garages allow for vehicles to come and go.

Think of a Stack like a deck of cards. You can add the cards, faced down, in random order and then start drawing off the top of the deck. The last card that was placed at the top of the deck will be the first card delt.

Class

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

Fiddle: Live Demo

Add Values

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

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

Fiddle: Live Demo

Remove Values

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

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

Fiddle: Live Demo

Exception

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

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