Array indexing?

qadeer37

Well-known member
Joined
May 1, 2010
Messages
63
Location
Hyderabad,pakistan
Programming Experience
1-3
Dim TwoDArray(1, 3) As Integer


For i As Integer = 0 To ThreeDArray.Length - 1

TwoDArray(i, i) = i + 1
ListBox1.Items.Add(ThreeDArray(i, i))

Next

This adds 1 and 2 to list. My question is why does the first element in the 2d array determines the length of an array and if we want to get the length 2nd index then what will be the method for that?:confused:
 
That code doesn't make any sense.

1. It won't even compile because you declare a variable named TwoDArray and then proceed to use a variable named ThreeDArray.

2. It throws an exception when you run it. Try this variation:
VB.NET:
Try
    Dim TwoDArray(1, 3) As Integer


    For i As Integer = 0 To TwoDArray.Length - 1

        TwoDArray(i, i) = i + 1
        ListBox1.Items.Add(TwoDArray(i, i))

    Next
Catch ex As Exception
    MessageBox.Show(ex.ToString)
End Try
and you'll see the exception clearly.

As the documentation states, the Length property gets the number of elements in ALL dimensions of the array. Your array is 2 by 4 so Length is 8. As soon as 'i' gets to 2 in your code the exception is thrown because there is no element at (2,2).

What exactly are you trying to accomplish? Are you trying to populate the entire array and put all the elements into a ListBox? If so then you will need to use two nested loops: one for each dimension. If you want to find the upper bound of a specific dimension then you use the GetUpperBound method.
 
Back
Top