Sometimes the data in your application is two-dimensional but not rectangular. As an example, you might have an array of months, each element of which is an array of days. Since different months have different numbers of days, the elements do not form a rectangular two-dimensional array. In such a case, you can use a jagged array instead of a multidimensional array, as the following example shows:
Dim Sales()() As Double = New Double(11)() {} ' Assign top-level array.
Dim Month As Integer ' Counter variable for month.
Dim Days As Integer ' Days in given month for this year.
For Month = 0 To 11
Days = DateTime.DaysInMonth(Year(Now), Month + 1) ' Get number of days.
Sales(Month) = New Double(Days - 1) {} ' Assign array for this month.
Next Month
The declaration of Sales sets the array
variable to a 12-element array, each element of which is an array of
Double elements. The For loop then determines how many days are
in each month this year (Year(Now)), and sets the corresponding
element of Sales to a Double array of the
appropriate length.
In the preceding example, the jagged array saves seven elements (six in a leap year) compared to a two-dimensional array. In a more extreme case the memory savings could be significant.
Note Jagged arrays are not compliant with the common language specification (CLS). This means you should not expose jagged arrays from any class you want CLS-compliant code to consume.
It is also possible to create an Object array and populate it with other arrays of different data types. The following code creates two arrays, one containing integers and the other strings. It then declares a third array of type Object and populates it with the integer and string arrays.
Dim I As Integer ' Counter variable. ' Declare and populate an integer array. Dim CountersA(4) As Integer ' Allocates five elements. For I = 0 To 4 CountersA(I) = I Next I ' Declare and populate a string array. Dim CountersB(4) As String ' Allocates five elements. For I = 0 To 4 CountersB(I) = "String number " & CStr(I) Next I ' Declare a new two-element array and populate it with the other arrays. Dim Counters(1) As Object' ' Elements (0) and (1). Counters(0) = CountersA Counters(1) = CountersB ' Display a member of each array. MsgBox(Counters(0)(2)) ' Displays "2". MsgBox(Counters(1)(3)) ' Displays "String number 3".
In the preceding example, the calls to MsgBox use late binding
on Counters(0) and Counters(1).
Counters(0)(2) is a specific object instance
created on Counters(0), and
Counters(1)(3) is an instance on Counters(1).
The Visual Basic compiler allows late binding only when Option Strict
is Off.