Page 173 - Open Soource Technologies 304.indd
P. 173
Unit 7: Arrays in Visual Basic
7.1.3 Static and Dynamic Arrays
Basically, you can create either static or dynamic arrays. Static arrays must include a fixed number
of items, and this number must be known at compile time so that the compiler can set aside the
necessary amount of memory. You create a static array using a Dim statement with a constant
argument:
‘ This is a static array.
Dim Names(100) As String
Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101
items.
Most programs don’t use static arrays because programmers rarely know at compile time how
many items you need and also because static arrays can’t be resized during execution. Both these
issues are solved by dynamic arrays. You declare and create dynamic arrays in two distinct steps.
In general, you declare the array to account for its visibility (for example, at the beginning of
a module if you want to make it visible by all the procedures of the module) using a Dim
command with an empty pair of brackets. Then you create the array when you actually need it,
using a ReDim statement:
‘ An array defined in a BAS module (with Private scope)
Dim Customers() As String
...
Sub Main()
’ Here you create the array.
ReDim Customer(1000) As String
End Sub
If you’re creating an array that’s local to a procedure, you can do everything with a single ReDim
statement:
Sub PrintReport()
This array is visible only to the procedure.
ReDim Customers (1000) As String
’ ...
End Sub
If you don’t specify the lower index of an array, Visual Basic assumes it to be 0, unless an Option
Base 1 statement is placed at the beginning of the module. My suggestion is this: Never use an
Option Base statement because it makes code reuse more difficult. (You can’t cut and paste
routines without worrying about the current Option Base.) If you want to explicitly use a lower
index different from 0, use this syntax instead:
ReDim Customers (1 To 1000) As String
Dynamic arrays can be re-created at will, each time with a different number of items. When you re-
create a dynamic array, its contents are reset to 0 (or to an empty string) and you lose the data it
contains. If you want to resize an array without losing its contents, use the ReDim Preserve command:
ReDim Preserve Customers (2000) As String
When you’re resizing an array, you can’t change the number of its dimensions nor the type of
the values it contains. Moreover, when you’re using ReDim Preserve on a multidimensional
array, you can resize only its last dimension:
LOVELY PROFESSIONAL UNIVERSITY 167