Results 1 to 4 of 4

Thread: Creating String Array

  1. #1

    Thread Starter
    Hyperactive Member Cyb3rH4Xter's Avatar
    Join Date
    May 2009
    Location
    Sweden
    Posts
    449

    Creating String Array

    Why doesn't this work?:


    Code:
    Dim sarray() As String = Nothing
    
    Dim inc As Integer = -1
    
    For each something in something
    
    inc += 1
    sarray.SetValue(something.value, inc) 'Error: Object reference not set to an instance of an object.
    
    Next
    plz help

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Creating String Array

    Because you are never creating an array. You are specifically stating that 'sarray' is Nothing and then you proceed to try to call SetValue on it. How can you call SetValue on Nothing?

    Arrays are fixed-size objects. To create an array you have to specify its size and that size doesn't change. If you want your list to grow and shrink as required then you need to use a collection. To create a "dynamic array" you would use a generic List, e.g.
    vb.net Code:
    1. Dim things As New List(Of String)
    2.  
    3. For Each thing In someList
    4.     things.Add(thing.Value)
    5. Next
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Hyperactive Member Cyb3rH4Xter's Avatar
    Join Date
    May 2009
    Location
    Sweden
    Posts
    449

    Re: Creating String Array

    thx!

  4. #4
    PowerPoster i00's Avatar
    Join Date
    Mar 2002
    Location
    1/2 way accross the galaxy.. and then some
    Posts
    2,390

    Re: Creating String Array

    kinda not directly related .... but...

    i don't know about .net ... but i usually avoid dynamic arrays as i come from vb6 where with an array if you wanted to add an item to an array you would need to redim (preserve) the array ... this would create a new array (in memory) with the newly specified amount of items and then copy the contents of the old array to it then replace the old array with the new one then destroy the old array (in memory behind the scenes)... as you may understand doing this could potentially be a lot slower than using a collection ...

    is this the same in .net? ... i guess i am asking is a list faster than an array to add / insert items to etc?

    kris

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width