tags:

views:

323

answers:

4

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
Made a minor correction in the code. ;-)
Cerebrus
*slow round of applause for cerebrus* that makes it MUCH more understandable :)
TheTXI
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
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
+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
+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
Good point, but existing array ... cann't split a string into a list of strings in one command can you ?
spacemonkeys
No, but you could call .ToList() on the result of String.Split.
Joel Coehoorn
Or List.AddRange()
Joel Coehoorn
+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