2

Lets say I want to create an array with 20 elements all set to a default value (let's say, 0)

But later, during runtime, I might want to resize the array. I might make it larger, to support 30 elements. The 10 new elements will have the default value of 0.

Or I might want to make my array smaller, to just 5. So I delete the complete the existence of the last 15 elements of the array.

Thanks.

2 Answers 2

2

ReDim Preserve will do it, and if the array were declared at the module level, any code referencing it will not lose the reference. I do believe this is specific to vb, however, and there is also a performance penalty, in that this, too, is creating a copy of the array.

I haven't checked, but I suspect the method user274204 describes above is probably the CLR-compliant way to do this . .

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Initialize your array: Dim Integers(20) As Integer 'Output to the console, and you will see 20 elements of value 0 Me.OutputArrayValues(Integers) 'Iterate through each element and assign an integer Value: For i = 0 To UBound(Integers) Integers(i) = i Next 'Output to console, and you will have values from 0 to 20: Me.OutputArrayValues(Integers) 'Use Redim Preserve to expand the array to 30 elements: ReDim Preserve Integers(30) 'output will show the same 0-20 values in elements 0 thru 20, and then 10 0 value elements: Me.OutputArrayValues(Integers) 'Redim Preserve again to reduce the number of elements without data loss: ReDim Preserve Integers(15) 'Same as above, but elements 16 thru 30 are gone: Me.OutputArrayValues(Integers) 'This will re-initialize the array with only 5 elements, set to 0: ReDim Integers(5) Me.OutputArrayValues(Integers) End Sub Private Sub OutputArrayValues(ByVal SomeArray As Array) For Each i As Object In SomeArray Console.WriteLine(i) Next End Sub 

End Class

Sign up to request clarification or add additional context in comments.

2 Comments

What looks like a lot of code is simply a bunch of comments explaining what is happening.
Note that, for multi-dimensional arrays, this only works for the last dimension. Here's a link with more info: msdn.microsoft.com/en-us/library/w8k3cys2(VS.71).aspx
0

It's not possible to resize an array (or any other object for that matter) once created.

You can use System.Array.Resize(ref T[], int) for a similar effect. However this will actually create a new array with the relevant portions copied across and may not be what you want if there are multiple references to the array scattered around.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.