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.
Resize notes. The Resize method logically allocates a new array, and then copies to it. You can use Array.Resize to develop your own resizable collections.
Shrink example. 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
Grow example. This program first declares an array of integers with 3 elements. Then, it displays the elements and also the array's total length.
Next The program invokes the Array.Resize subroutine. This makes the new length of the array 6.
And There are now 3 elements at the end of the example array that were not there before.
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
Zero elements. 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.
Also For strings the default value will be Nothing, because no objects were allocated for the new references.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 27, 2021 (image).