What is the best way to clear an array of strings?
+3
A:
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)
Micah
2009-04-03 13:23:14
Made a minor correction in the code. ;-)
Cerebrus
2009-04-03 13:26:44
*slow round of applause for cerebrus* that makes it MUCH more understandable :)
TheTXI
2009-04-03 13:27:14
That doesn't clear the array - it sets the variable to Nothing. Anything else referring to the same array will still see the existing values.
Jon Skeet
2009-04-03 13:35:23
Thanks ... I had actually done the Array.clear, but something was telling me there was a more efficiant short hand way .... not end of the world stuff, but was really bugging me lunch time
spacemonkeys
2009-04-03 16:24:26
+1
A:
Depending what you want:
- Assign Nothing (null)
- Assign a new (empty) array
- Array.Clear
Last is likely to be slowest, but only option if you don't want a new array.
Richard
2009-04-03 13:23:46
+2
A:
If you're needing to do things like clear, you probably want a collection like List(Of String)
rather than an array.
Joel Coehoorn
2009-04-03 13:31:47
Good point, but existing array ... cann't split a string into a list of strings in one command can you ?
spacemonkeys
2009-04-03 19:44:43
+1
A:
And of course there's the VB way using the Erase keyword:
Dim arr() as String = {"a","b","c"}
Erase arr
Dustin Campbell
2009-04-03 13:35:07