Arrays are one variable that can carry a series of one datatype. To declare an array we can simply use this formatting:
If we know the number of elements entering the array, but not the values of the elements themselves, we can declare an array without setting the values. Here is an example of an array of 3 strings without values.
Some arrays are more than one-dimensional. By this, I mean they are not simply a line of elements. If you are defining a two-dimensional array, you must declare the values regarding BOTH dimensions of the array. Here is an example of a two-dimensional array of Integers:
1 (0,0) | 2 (0,1) |
3 (1,0) | 4 (1,1) |
5 (2,0) | 6 (2,1) |
7 (3,0) | 8 (3,1) |
This code would create the array to the right. When specifying a position in a two-dimensional array, the first number represents the row, while the second number represents the column. The comma is to show that this is a two-dimensional array. However, it does not define how many objects are in the array.
Array retrieval and storage is always 0-based. Therefore, using our above example, the following code would result in Example having a value of 2.
If you need to resize an array in VB, you use the ReDim word. Here is an example of this:
However, this formats the array, deleting all of the values. To fix this, we use “Preserve” like this:
NOTE: When using Preserve, you cannot ReDim the first number (the row). This will create a runtime error.
As you’d probably guess, Arrays are not very useful unless you know the number of elements beforehand. Because of this, many people prefer ArrayLists, which is next.
Previous Next