Visual Basic Stacks

Stacks in Visual Basic, like queues, are similar to both arrays and lists, with their ability to hold multiple values of the same type, however, the order of the elements in a stack is set by the order they are added to the stack and cannot be altered. A stack can be compared to a real-life stack of books on a table. Books are added to the top of the stack, with the first item to be removed being the last that was added. Due to this behaviour, a stack is known as a Last-In First-Out, or LIFO, data structure.

Below is an example of how a stack, called ‘fname’, that contains string values, can be declared.

Dim fname As Stack(Of String) = New Stack(Of String)()

In order to add items to a stack, the ‘Push’ method must be used.


Here, four names have been added to the stack.

It is possible to see how many items there are in the stack using the ‘Count’ property of the stack itself.


In order to see the items in a stack, without actually removing them, a ‘For Each’ loop can be used in a similar way as with arrays, lists and queues.

For Each name As String In fname

This will display each name in the stack on a separate line in the console, in the order that the values will be removed, the reverse of how they were added.


If it is required to see just the next item in the stack without removing it, then the ‘Peek’ method can be used.


As well as being able to see the next item, there is also the functionality to check to see if a particular value exists in a stack. This is achieved using the ‘Contains’ method.


The above example checks to see if the value, ‘George’, exists in the stack and returns a Boolean True or False value.

In order to remove individual items from a stack, the ‘Pop’ method can be utilised. The example below assigns the number of items in the stack to a variable. This value is then used to limit the number of iterations in a ‘For’ loop. Within the loop the ‘Pop’ method is used to remove an item from the stack, display it in the console and output the number of items left in the stack.

Dim fname As Stack(Of String) = New Stack(Of String)()


Dim stackHeight As Integer = fname.Count

Console.WriteLine("Items in stack: {0}", stackHeight)

For i = 1 To stackHeight

    Console.WriteLine("Next item from stack: {0}", fname.Pop())
    Console.WriteLine("Items left in stack: {0}", fname.Count)


The resulting output is shown below.

Items in stack: 4

Next item from stack: Alan
Items left in stack: 3

Next item from stack: Fred
Items left in stack: 2

Next item from stack: George
Items left in stack: 1

Next item from stack: Bob
Items left in stack: 0

Finally, if it is necessary to remove all items in a stack in one go, instead of individually with the ‘Pop’ method, there is a ‘Clear’ method to accomplish this.