4.5. ArraysThe array is a fundamental data structure in many programming languages, including Visual Basic. Arrays store a collection of similar data types or objects. Each element has a numbered position, ranging from 0 (the lower bound) to the defined upper bound of the array. The following examples show various ways to declare a one-dimensional array: ' Implicit constructor: No initial size and no initialization Dim days( ) As Integer ' Explicit constructor: No initial size and no initialization Dim days( ) As Integer = New Integer( ) {} ' Implicit constructor: Initial size but no initialization Dim days(6) As Integer ' Explicit constructor: Initial size but no initialization Dim days( ) As Integer = New Integer(6) {} ' Implicit constructor: Initial size implied by initialization Dim days( ) As Integer = {1, 2, 3, 4, 5, 6, 7} ' Explicit constructor, Initial size and initialization Dim days( ) As Integer = New Integer(6) {1, 2, 3, 4, 5, 6, 7} Array declarations can:
In VB 6, the programmer could specify both the lower and upper bounds of any array dimension. With .NET, all Visual Basic arrays have a lower bound of zero. The statement: Dim myArray(5) As Integer declares an array with six elements, numbered zero through five. Arrays can include multiple dimensions. The following example declares and initializes a two-dimensional array: Dim rectArray(,) As Integer = {{1, 2, 3}, {4, 5, 6}} The following code displays the contents of this array: Debug.Write(rectArray(0, 0)) Debug.Write(rectArray(0, 1)) Debug.WriteLine(rectArray(0, 2)) Debug.Write(rectArray(1, 0)) Debug.Write(rectArray(1, 1)) Debug.WriteLine(rectArray(1, 2)) ' ----- The output is: 123 456 The upper bound of any array dimension can be modified using the ReDim statement. ReDim [Preserve] arrayName(newUpperBound) The Preserve qualifier retains any existing values in the array; all array elements are cleared in the absence of this qualifier. When using Preserve, only the last dimension of an array can have its upper bound modified. The number of dimensions in an array cannot be changed. You can determine the lower and upper bounds of an array dimension using the LBound and UBound functions respectively. Dim smallArray(5) As Integer MsgBox(UBound(smallArray)) ' Displays "5" Since all array dimensions have a lower bound of zero, the LBound function always returns zero. |