question

MosheMaor-7929 avatar image
0 Votes"
MosheMaor-7929 asked BobJohnson-6874 edited

Bad array declaration

Hello everybody,
VERY simple question. Lately I do not use arrays, but lists, which are more efficient. So maybe I forgot something basic about arrays.
'-----------------------------------
This simple code creates an error. The definition of the array is wrong.
The error I get is: Use the "new" keyword to create a object instance.
So, what is wrong is the array declaration?

 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

     Dim Arr() As String      
     Dim n As Integer
     For n = 1 To 5
         Add_to_Array(Arr, n.ToString)
     Next
 End Sub

 Public Sub Add_to_Array(ByRef Arr() As String, ByVal s As String)
     Array.Resize(Arr, Arr.Length + 1)
     Arr(Arr.Length - 1) = s

    ' This probably work too
    ' ReDim Preserve Arr(UBound(Arr) + 1)
    ' Arr(UBound(Arr)) = s
 End Sub

'---------------------------------
Thanks ahead to all helpers,
Moshe.

azure-webapps-development
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered MosheMaor-7929 commented

I think that one of the solutions is:

 Sub Add_to_Array(ByRef Arr() As String, ByVal s As String)
     If Arr Is Nothing Then
         Arr = {}
     End If
     Array.Resize(Arr, Arr.Length + 1)
     Arr(Arr.Length - 1) = s
 End Sub

Or you can create the initial empty array:

 Dim Arr() As String = { }

Then Add_to_Array does not need adjustments.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello Viorel,
Your answer solves the problem, of course.
I have adopted the line: Dim Arr() As String = { }
I have worked with array for years, and did not encounter such a problem.
Now I know why. For simplicity, I have never used the 0 index cell in an array.
All my loops started with cell 1.
Now, when I use more and more the For .. each loop, index 0 can not be ignored
easily, otherwise I use an If statement, which is a bad idea.
Thank you for your fast and helpful answer.
Moshe.

0 Votes 0 ·