C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
LIFO: The last element added to the Stack is the first element removed from the Stack. All activity occurs on the top of the stack.
VB.NET program that uses Stack
Module Module1
Sub Main()
Dim stack As Stack(Of Integer) = New Stack(Of Integer)
stack.Push(10)
stack.Push(100)
stack.Push(1000)
' Display stack elements.
For Each value As Integer In stack
Console.WriteLine(value)
Next
End Sub
End Module
Output
1000
100
10
Peek: With Peek, you take the top element and copy it to the return value, but it is not removed.
Count: To avoid exceptions with an empty stack, use the Count property and test it against zero.
VB.NET program that uses Pop and Peek
Module Module1
Sub Main()
Dim stack As Stack(Of Integer) = New Stack(Of Integer)
stack.Push(10)
stack.Push(100)
stack.Push(1000)
' Test Pop.
Dim value As Integer = stack.Pop
Console.WriteLine("Element popped: {0}", value)
' Test Peek.
value = stack.Peek
Console.WriteLine("Element peeked: {0}", value)
End Sub
End Module
Output
Element popped: 1000
Element peeked: 100
Next: We use the Contains function, which works in much the same way as the List Contains function. It returns True or False.
ListVB.NET program that uses Stack constructor and Contains
Module Module1
Sub Main()
Dim array(2) As String
array(0) = "dot"
array(1) = "net"
array(2) = "Codex"
' Copy array to a new stack.
Dim stack As Stack(Of String) = New Stack(Of String)(array)
' Use Contains.
Console.WriteLine(stack.Contains("net"))
Console.WriteLine(stack.Contains("not"))
End Sub
End Module
Output
True
False
Note: Stacks are useful in any system where the most recently added element is the most urgent.
Thus: The VB.NET Stack type is used to implement a variety of important algorithms.