array in a class - object reference not set to an instance

lamy

Regular
Joined
Dec 12, 2005
Messages
56
Location
under your bed
im trying to make a class with an array object in it but somehow reference is lost whenever i add a new item to it

Visual Basic:
    Public Class MyMenu
        Public parent()() As String
        Public Function AddParent(ByVal title As String, ByVal link As String) As Int16
            Dim id As Int16 = 0
            If Not parent Is Nothing Then
                id = parent.Length
            End If

            ReDim parent(id)

            parent(id) = New String() {title, link}

            Return id
        End Function
    End Class

doing this works
Visual Basic:
        Dim id As Int16

        id = m.AddParent("1", "1.htm")
        MsgBox(m.parent(0)(1))
        id = m.AddParent("2", "2.htm")
        MsgBox(m.parent(1)(1))
        id = m.AddParent("3", "3.htm")
        MsgBox(m.parent(2)(1))
but this doesnt

Visual Basic:
        Dim id As Int16

        id = m.AddParent("1", "1.htm")
        id = m.AddParent("2", "2.htm")
        id = m.AddParent("3", "3.htm")
        MsgBox(m.parent(0)(1))
        MsgBox(m.parent(1)(1))
        MsgBox(m.parent(2)(1))

anyone?
 
You will probably need to use Redim Preserve parent(id) - otherwise it doesn't keep the array contents.

Also you might find the code cleaner if you create a class or structure to manage the pair of strings as a single item rather than creating an array of a string array.
Also you may want to look at using a collection class rather than an array as constantly redimming an array can cause unnecessary memory allocations / deallocations.
 
Back
Top