Jump to content
Xtreme .Net Talk

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


Recommended Posts

Posted

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

 

   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

       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

 

       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?

slow down when you need to hurry, stop when you need to move on,

look back when you need to forget, or you might slip and leave sanity

  • Administrators
Posted

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.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...