ProblemYou 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. SolutionSample 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. DiscussionActually, 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 PreserveOne 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 AlsoRecipe 8.4 shows how to insert elements into the middle of an existing array, instead of just at the end. |