Resize an Array

Problem

You need to expand the dimensions of an array.

Solution

The Visual Basic .NET ReDim statement with the Preserve keyword.

Discussion

The ReDim keyword allows you to specify new dimensions for an array after defining it. However, the existing items will be lost, unless you specify the Preserve keyword. When using Preserve, you can only resize the last dimension of the array. Thus, if you are resizing a two-dimensional array, you can only expand the second dimension. If you are resizing a one-dimensional array, you can resize the first (and only) dimension.

Dim IntArray(10, 10) As Integer ' (Configure the array here.) ' Add ten more columns to every row ReDim Preserve IntArray(10, 20) ' The following statement will generate an exception. ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.