In Visual Basic, arrays are a structure of fixed or variable length that stores elements of the same type. Dynamic arrays particularly require attention during initialization and resizing.
In VB6, there were only static and dynamic arrays with fixed or variable size. VB.NET implements full one-dimensional, multi-dimensional, and jagged arrays of any type with type safety.
Common errors include—
Always initialize the array before use and carefully resize it:
' Declaration Dim arr() As Integer ' Initialization ReDim arr(4) ' Indices 0–4 arr(0) = 1 ' Resizing while preserving values ReDim Preserve arr(6)
Key features:
What happens if you declare an array but do not initialize it?
For one-dimensional arrays like Dim arr() As Integer, the variable exists, but the array itself is not allocated; accessing arr.Length will raise an exception.
Can ReDim Preserve be used to resize a multi-dimensional array in both dimensions?
No, ReDim Preserve only allows resizing the last dimension; otherwise, it will throw a runtime error.
What happens to the elements of the array when increasing its size via ReDim Preserve?
Old values will be preserved, and new elements will receive default values (e.g., 0 for Integer, Nothing for reference types).
** Negative Case
The array is declared but not initialized (Dim arr() As Integer), and when accessing arr.Length, a NullReferenceException occurs.
Pros:
Cons:
** Positive Case
The array is always explicitly initialized through ReDim, resizing is done only outside the main loop, and for frequently changing lists, List(Of Integer) is used.
Pros:
Cons: