What is the best way to clear an array of strings?
And of course there's the VB way using the Erase keyword:
Dim arr() as String = {"a","b","c"}
Erase arr
redim arr(1,1,1,1) and then redim (z,x,y,v) to your dimensions
If you're needing to do things like clear, you probably want a collection like List(Of String)
rather than an array.
If you need to reinitialize with empty strings or other values not equal to Nothing/Null, you may get further using an extension method:
Option Strict On : Option Explicit On : Option Infer On
...
Public Delegate Sub ArrayForAllDelegate(Of T)(ByRef message As T)
<Extension>
Public Function ForAll(Of T)(ByRef self As T(), f As ArrayForAllDelegate(Of T)) As T()
Dim i = 0
While i < self.Length
f(self(i))
i += 1
End While
Return self
End Function
Then your initialization code:
Dim a = New String(3 - 1) {"a", "b", "c"}
...
a.ForAll(Sub(ByRef el) el = "") 'reinitialize the array with actual empty strings
Wrong way:
myArray = Nothing
Only sets the variable pointing to the array to nothing, but doesn't actually clear the array. Any other variables pointing to the same array will still hold the value. Therefore it is necessary to clear out the array.
Correct Way
Array.Clear(myArray,0,myArray.Length)
Here's a simple call that I use to clear the contents of a string array:
Public Sub ClearArray(ByRef StrArray As String())
For iK As Int16 = 0 To StrArray.Length - 1
StrArray(iK) = ""
Next
End Sub
Then just call it with:
ClearArray(myLocalArray)