Bagikan melalui


Jagged Arrays in Visual Basic

An array of which each element is itself an array is called an array of arrays, or a jagged array. Note that having arrays as elements is not the same thing as a multidimensional array, which has more than one index on a single array.

Meaning of Jagged

Sometimes the data structure in your application is two-dimensional but not rectangular. For 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.

Example

The following example declares an array variable to hold an array of arrays with elements of the Double Data Type (Visual Basic). Each element of the array sales is itself an array that represents a month. Each month array holds values for each day in that month.

Dim sales()() As Double = New Double(11)() {}
Dim month As Integer
Dim days As Integer
For month = 0 To 11 
    days = DateTime.DaysInMonth(Year(Now), month + 1)
    sales(month) = New Double(days - 1) {}
Next month

The New clause in the declaration of sales sets the array variable to a 12-element array, each element of which is of type Double(), 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 size.

In the previous example, the jagged array saves seven elements (six in a leap year) as compared to a two-dimensional array. In a more extreme case the memory savings could be significant.

See Also

Tasks

How to: Declare an Array Variable

How to: Create an Array of Arrays

How to: Initialize a Jagged Array

Troubleshooting Arrays

Concepts

Overview of Arrays in Visual Basic

Array Dimensions in Visual Basic

Multidimensional Arrays in Visual Basic

Array Data Types in Visual Basic

Writing CLS-Compliant Code

Other Resources

Arrays in Visual Basic