DannyF247
DannyF247

Reputation: 638

VB.NET Multi-Dimentional Array

Alright, so I'm used to PHP where I can declare a multi-level array like $something[0][1] = "test";. I need to be able to accomplish the same thing, but I'm using VB.NET. How would I do this?

And sorry if this isn't what a multi-dimentional array is, I might be wrong at what it's called but that's what I want to do.

Thanks!

Upvotes: 0

Views: 3750

Answers (2)

codeConcussion
codeConcussion

Reputation: 12938

Multidimensional array in VB.Net...

Dim twoDimensionalArray(10, 10) As String
twoDimensionalArray(0, 1) = "test"

I rarely use arrays, however. More elegant solutions can typically be achieved using Lists, Dictionaries, or combinations of the two.

Update .

The (10, 10) is the upper bound of the array (the size is actually 11, 0 through 10). If you don't specify the bounds, you have to Redim Preserve the array when you want to add to it. That's one good thing about lists, you don't have to specify an initial size and you can add to them freely.

Here's a quick example of a list of lists.

Dim listOfLists As New List(Of List(Of String))
listOfLists.Add(New List(Of String)(New String() {"a", "b", "c"}))
listOfLists.Add(New List(Of String)(New String() {"d", "e", "f"}))
listOfLists.Add(New List(Of String)(New String() {"g", "h", "i"}))
'listOfLists(0)(0) = "a"
'listOfLists(0)(1) = "b"
'listOfLists(2)(1) = "h"

Upvotes: 1

Nicholas
Nicholas

Reputation: 754

Just a plain sample with dynamic resizing of the array

Dim arr(0)() As String            '** array declaration 
For i As Integer = 0 To 100       '** Outer loop (for the 1st dimension)
   For j As Integer = 0 To 1      '** inner loop (for the 2nd dimension)
      ReDim Preserve arr(i)       '** Resize the first dimension array preserving the stored values
      ReDim Preserve arr(i)(j)    '** Resize the 2nd dimension array preserving the stored values
      arr(i)(j) = String.Format("I={0},J={1}", i, j) '** Store a value 
   Next                           
Next

In .NET Arrays are usually static and won't be automatically resized. (As for example in Javascript etc.) Therefore it's necessary to manually resize the array each time you want to add a new item, or specify the size at the beginning.

Upvotes: 0

Related Questions