Array.Resize
A VB.NET array can be resized. This will either remove elements at the end if you resize it to be smaller, or add elements at the end if you resize it to be bigger.
The Resize method logically allocates a new array, and then copies to it. You can use Array.Resize
to develop your own resizable collections.
To begin, we use Array.Resize
on a 4-element integer array. We reduce (shrink) the size to 2 elements. The last 2 elements are erased.
Module Module1 Sub Main() ' Create an array. Dim arr(3) As Integer arr(0) = 10 arr(1) = 20 arr(2) = 30 arr(3) = 40 ' Call Array.Resize to shrink the array. Array.Resize(arr, 2) ' Display. For Each value As Integer In arr Console.WriteLine(value) Next End Sub End Module10 20
This program first declares an array of integers with 3 elements. Then, it displays the elements and also the array's total length.
Array.Resize
subroutine. This makes the new length of the array 6.Module Module1 Sub Main() ' Create array of three elements. Dim arr(2) As Integer arr(0) = 1 arr(1) = 2 arr(2) = 3 ' Display all elements and the length. For Each value As Integer In arr Console.Write(value) Console.Write(" ") Next Console.Write("- ") Console.WriteLine(arr.Length) ' Call Array.Resize. Array.Resize(arr, 6) ' Display all elements and the length. For Each value As Integer In arr Console.Write(value) Console.Write(" ") Next Console.Write("- ") Console.WriteLine(arr.Length) End Sub End Module1 2 3 - 3 1 2 3 0 0 0 - 6
Why are the elements zero? The default value of an integer on the heap is the value zero. All the bits are set to zeros.
Array.Resize()
is used in many collections. When a collection such as a List
or Dictionary
needs to become larger, it calls Array.Resize
to resize its internal buffers, which are arrays.