Reputation: 456
When I rebuild the solution I get the warning:
"Variable 'aMyArray' is used before it has been assigned a value."
A function in VB.NET uses an array which is dynamically populated.
Example:
Function MyArray()
Try
Dim aMyArray()
For i = 0 to 100
ReDim Preserve aMyArray(i)
Next
Catch ex As Exception
End Try
End Function
How should I declare a dynamically populated array to eliminate this warning?
Upvotes: 1
Views: 5215
Reputation: 38875
A. Your function returns nothing, so you should also have a warning about that
B. You seriously need to turn on Option Strict
and let the compiler point out other errors like aMyArray has no Type.
C. Never use and empty Try/Catch
; if there is an exception, you want to know when something goes wrong (and where) so you can fix it.
D. Avoid arrays like the plague. ReDim Preserve aMyArray(i)
creates a new array and then copies all the data to the new structure. This can be costly in terms of performance if it is a large array of something like strings. Net has several very nice collections such as List(of T)
which do not need to be explicitly resized:
Private myList As New List(of String) ' or Integer, Decimal or even MyClassObject
...
myList.Add("Hello")
myList.Add("Lists...")
myList.Add("Goodbye")
myList.Add("Arrays")
D(1). The result of using a List
would mean that entire procedure can be done away with. Just add new things to the list as needed.
E. The code posted cant actually result in the warning because you dont ever add a value to it. Adding: aMyArray(2) = 2
after the loop will result in the warning. This is because you have never fully declared the array (size and type) as in:
Dim aMyArray(100) As String
ReDim
simply resizes the array which isnt the same thing.
F. Since there is nothing in your new array, there is no reason to use ReDim Preserve
because there is nothing to preserve. I'll assume that is supposed to be some calculation. On the other hand, if you are trying to resize an existing array, it should be a Sub.
We are all left to guess if it really is meant to modify an existing array (based on ReDim Preserve
) or return a new array of stuff (considering the array is declared in the procedure).
Again, none of this is needed using a List
, Dictionary
or other Collection Type.
Upvotes: 2
Reputation: 5545
I like to use the CreateInstance to avoid possible errors:
Dim aMyArray() as string = Array.CreateInstance(GetType(String),0)
Upvotes: 2