Share via

Bad array declaration

Moshe Maor 21 Reputation points
2021-05-26T16:19:04.917+00:00

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 App Service
Azure App Service

Azure App Service is a service used to create and deploy scalable, mission-critical web apps.

0 comments No comments

Answer accepted by question author

Viorel 127K Reputation points
2021-05-27T07:50:58.103+00:00

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.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.