Stack in Visual Basic .NET

August 24, 2017

Stack is a collection of objects which you can add element to top of the stack and you can remove the element from the top

So Stack represents a simple last-in-first-out (LIFO) non-generic collection of objects.

When you add element to stack you call it PUSH
When you remove element from stack you call it POP

We will write small piece of code in VB.NET for Stack operations

Module Module1

    Sub Main()
        Dim dayStack As New Stack

        dayStack.Push("Tuesday")
        dayStack.Push("Monday")
        dayStack.Push("Sunday")

        For Each element In dayStack
            Console.WriteLine(element)
        Next

        'Removing item from stack
        dayStack.Pop()

        Console.WriteLine("---------- After Removing Element")
        For Each element In dayStack
            Console.WriteLine(element)
        Next


        Console.ReadLine()
    End Sub

End Module

Output

Sunday
Monday
Tuesday
---------- After Removing Element
Monday
Tuesday

Code explanation

Line 4: Defining the Stack
Line 6: PUSH the element to stack
Line 15: POP the element from stack
When you look at the output last added item is “Sunday” and it is removed first