How to iterate a jagged array?

Akira picture Akira · Sep 8, 2008 · Viewed 8.6k times · Source

This has been driving me crazy for a few days. Why doesn't the following work?

    Dim arr(3, 3) As Integer

    For y As Integer = 0 To arr.GetLength(0) - 1
        For x As Integer = 0 To arr.GetLength(y) - 1
            arr(y, x) = y + x
        Next
    Next

Also, what if the array looked like this instead?

{ {1, 2, 3},
  {4, 5, 6, 7, 8, 9, 9, 9},
  {5, 4, 3, 2}
}

Answer

Joel Coehoorn picture Joel Coehoorn · Sep 8, 2008

Because there is no '2' or '3' dimension. Should be .GetLength(1) instead of .GetLength(y)

Also: in VB.Net array declarations work a little differently. The subscript you specify in the declaration is the last index, not the number of items created like with C# or C++. But the array is still 0-indexed like C# or C++, instead of 1-indexed like VB6. That means that if you move to VB.Net from a different language your array instincts are probably wrong, no matter which language it is. In VB.Net, Dim arr(3,3) As Integer actually creates a 4x4 array.