A. Arrays

i.  Filling an Array While Declaring It

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}}

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

ii. Iterating Through Array Elements

The For Each line declares a temporary variable named that exists only for the duration of the For Each loop. This ties the variable name closely to the processing going on locally and frees up resources as soon as that processing is completed. Also, there is no need to access the length of the array to control the looping because the loop implicitly processes all elements, no matter what the array’s size is. (The standard For loop syntax requires a separate counting variable and access to the array’s length.)

iii. Returning Arrays from Functions

An Array could be created from a Function of a desired data type and returned in the Return Statement as a collection.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: