Virtual Stack

This demonstrates how to implement a virtual stack class.

'This is a virtual stack class
Public Class VStack
    Dim cStackItems As New Collection()
    Dim iItemCount As Int32          ' The size of the stack (-1 = dynamic size, 0 = empty)
    Public Sub New()
        iItemCount = -1 ' This stack will be dynamic
    End Sub
    Public Sub New(ByVal iSize As Int32)
        iItemCount = iSize
    End Sub
    'Public Sub New(ByVal iSize As Int32, ByVal oTemplate As Object)
    '    iItemCount = iSize
    '    ' Put template in all items
    '    Dim i As Int32
    '    For i = 0 To iItemCount - 1
    '        cStackItems.Add(oTemplate)
    '    Next
    'End Sub
    Public Sub Push(ByVal oItem As Object)
        If cStackItems.Count < iItemCount Or iItemCount = -1 Then
            cStackItems.Add(oItem)
        ElseIf cStackItems.Count = iItemCount Then
            Throw New OverflowException("Not enough room on the virtual stack.")
        End If
    End Sub
    Public Function Pop() As Object
        Dim oTemporaryItem As Object
        Try
            oTemporaryItem = GetItem()
            cStackItems.Remove(cStackItems.Count) ' delete the last item
            Return oTemporaryItem
        Catch e As IndexOutOfRangeException
            Throw e
        Catch e As Exception
            Throw e
        End Try
    End Function
    Public Function Peek() As Object ' Like a pop, but doesn't delete the item
        Dim oTemporaryItem As Object
        Try
            oTemporaryItem = GetItem()
            Return oTemporaryItem
        Catch e As IndexOutOfRangeException
            Throw e
        Catch e As Exception
            Throw e
        End Try
    End Function
    Public Function GetItem() As Object
        If cStackItems.Count >= 1 Then
            Return cStackItems.Item(cStackItems.Count) ' get the most recent item
        Else
            Throw New IndexOutOfRangeException("No items on the stack.")
        End If
    End Function
    Public ReadOnly Property CurrentSize() As Int32
        Get
            Return cStackItems.Count
        End Get
    End Property
    Public ReadOnly Property MaxItems() As Int32
        Get
            Return iItemCount
        End Get
    End Property
End Class

You might also like...

Comments

Daniel Okely -Daniel Okely Inaugural Developerfusion.com Prize Winner

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.” - Antoine de Saint Exupéry