Recipe 8.1. Filling an Array While Declaring It


Problem

You want to fill an array with starting values without having to explicitly assign each array element individually.

Solution

You can load an array in the Dim statement using empty parentheses after either the array's name or its type designation, followed by braces listing the array elements to be assigned.

Discussion

The following line of code creates a one-dimensional array of integers with three elements (elements 0 through 2):

 Dim array1D( ) As Integer = {1, 2, 3} 

A two-dimensional array is only slightly trickier to fill on the spot, requiring nested braces containing the array elements. You can put the nested braces all on one line, or you can use the underscore line-continuation symbol to format the data in a more readable layout, such as in the following example:

 Dim array2D(,) As Integer = { _    {1, 2}, _    {3, 4}} 

For comparison, the following line of code creates exactly the same array:

 Dim array2D(,) As Integer = {{1, 2}, {3, 4}} 

Arrays with three or more dimensions are declared in a similar way, with additional commas and curly braces included as needed:

 Dim array3D(,,) As Integer = _    {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}} 

For comparison, the following block of code creates exactly the same three-dimensional array and fills each element with the same values, but does so using a more traditional method of assigning each individual element:

 Dim array3D(1, 1, 1) As Integer array3D(0, 0, 0) = 1 array3D(0, 0, 1) = 2 array3D(0, 1, 0) = 3 array3D(0, 1, 1) = 4 array3D(1, 0, 0) = 5 array3D(1, 0, 1) = 6 array3D(1, 1, 0) = 7 array3D(1, 1, 1) = 8 




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net