1

I need to create an array of string arrays. Example:

> Array(0) = {"1", "a", "e"} 

> Array(1) = {"word", "at", "war"} 

> ...

I did:

Dim array()() As String

For i = 0 to 10
    array(i) = New String() {"dfdd", "dda", "aa", "bnb", "3", "ghj", "ht"}
Next i

But it fails with the exception:

Object reference not set to an instance of an object.

levi
  • 22,001
  • 7
  • 73
  • 74
Carol
  • 553
  • 2
  • 10
  • 24
  • Duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Bjørn-Roger Kringsjå Feb 16 '15 at 18:22
  • You are initializing the child elements with `New String() {...}` inside the loop, but the "parent" array is not initialized. – Nate Barbettini Feb 16 '15 at 18:23
  • That's what Im trying to know :S, Because If I try: Dim array()() As String = New String() it gives to me error. I dont know how to declarate this kind of arrays without creating and structure or a class – Carol Feb 16 '15 at 18:28
  • 2
    If you really want to use arrays: `Dim array As String()() = New String(10)() {}` – Bjørn-Roger Kringsjå Feb 16 '15 at 18:31

4 Answers4

4

It's because the first dimension of your array was not initialized.

    Dim array(10)() As String

    For i = 0 To 10
        array(i) = New String() {"dfdd", "dda", "aa", "bnb", "3", "ghj", "ht"}
    Next I

I would suggest you look at List and maybe create a class instead if each string determine a different property.

the_lotus
  • 12,668
  • 3
  • 36
  • 53
3

I think that a List(Of String()) would suit your needs better here:

Dim arrays as New List(Of String())

For i = 0 to 10
    arrays.Add(New String() {"dfdd", "dda", "aa", "bnb", "3", "ghj", "ht"})
Next i

A List will automatically expand to hold as many arrays as you need. Then, if you still want an array of arrays, you can always do:

arrays.ToArray()

Here's a fiddle. Also, see this answer to a similar question about byte arrays.

Community
  • 1
  • 1
Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
0

You can always do it this way:

Dim array = Enumerable _
    .Range(0, 10) _
    .Select(Function (n) New String() {"dfdd", "dda", "aa", "bnb", "3", "ghj", "ht"}) _
    .ToArray()
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0
Public Function ArrayToSV(ByVal array() As Object, ByVal seperator As Char) As String
    Dim i As Integer
    Dim tmpstr As String
    tmpstr = CStr(array(LBound(array)))
    For i = LBound(array) + 1 To UBound(array)
        tmpstr = tmpstr & seperator & CStr(array(i))
    Next
    Return tmpstr
End Function

This method will give you the desired result, provide a Object Array and Separator it will return a string.

DareDevil
  • 5,249
  • 6
  • 50
  • 88