Visual Basic .NET - Stack

In VB.NET, the Stack class is used to implement a last-in-first-out (LIFO) collection of objects. It is defined in the System.Collections namespace. Elements are pushed onto the top of the stack using the Push method, and popped from the top of the stack using the Pop method. The Peek method can be used to retrieve the topmost element without removing it.

' Create a new Stack object
Dim myStack As New Stack()
' Push elements onto the stack
myStack.Push("apple")
myStack.Push("banana")
myStack.Push("cherry")
' Pop elements from the stack
Dim element As String = myStack.Pop()
Console.WriteLine("Popped element: " & element)
' Peek at the topmost element
element = myStack.Peek()
Console.WriteLine("Top element: " & element)
' Check if the stack contains an element
If myStack.Contains("banana") Then
    Console.WriteLine("Stack contains 'banana'")
End If
' Get the number of elements in the stack
Dim count As Integer = myStack.Count
Console.WriteLine("Number of elements in stack: " & count)
' Clear all elements from the stack
myStack.Clear()
Console.WriteLine("Cleared all elements from stack")


'Output:
'Popped element: cherry
'Top element: banana
'Stack contains 'banana'
'Number of elements in stack: 2
'Cleared all elements from stack

In the example above, we create a new Stack object and push three elements onto it. We then pop an element from the top of the stack and print it out, peek at the topmost element without removing it and print it out, check if the stack contains an element and print a message if it does, get the number of elements in the stack and print it out, and finally clear all elements from the stack and print a message.