Recipe 8.7. Resizing Arrays Without Losing Existing Values


You want to add an unknown number of elements to an array, resizing the array as needed, but you don't want to lose any data in the process.


Sample code folder: Chapter 08\SwapArrayElements

Visual Basic 2005 provides the ReDim Preserve command to resize an array without losing any of the array's current contents.


Actually, you can lose some contents of an array using ReDim Preserve, but only if you are decreasing the array's size. ReDim Preserve is most often used to grow an array, and it is ideal for adding new elements on the fly, without losing any data already in the array.

For example, the following code creates an integer array and then loops to grow it one element at a time. A number is stored in each new array element as the array grows:

 Dim result As New System.Text.StringBuilder Dim growingArray( ) As String = Nothing ' ----- Add elements to the array. For counter As Integer = 0 To 2    ReDim Preserve growingArray(counter)    growingArray(counter) = (counter + 1).ToString Next counter ' ----- Display the results. For Each workText As String In growingArray    result.AppendLine(workText) Next workText MsgBox(result.ToString( )) 

Figure 8-7 displays the simple integer array that was resized, one element at a time, to hold the three numbers shown.

Figure 8-7. Resizing an array on the fly with ReDim Preserve

One nice thing about ReDim Preserve is that it works with arrays that are empty or set to Nothing, as shown in the sample code.

The Array object's Resize() method provides similar functionality.

See Also

Recipe 8.4 shows how to insert elements into the middle of an existing array, instead of just at the end.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: