17

What is the easiest way to clear an array of strings?

1
  • 2
    clear an array? what do you mean be clear? Commented Sep 26, 2010 at 12:45

8 Answers 8

46

Have you tried Array.Clear?

string[] foo = ...;
Array.Clear(foo, 0, foo.Length);

Note that this won't change the size of the array - nothing will do that. Instead, it will set each element to null.

If you need something which can actually change size, use a List<string> instead:

List<string> names = new List<string> { "Jon", "Holly", "Tom" };
names.Clear(); // After this, names will be genuinely empty (Count==0)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I couldn't understand why I couldn't find clear under string methods. The answer, of course, is that it's an array method.
I should probably know this by now but if you just set the string array to null does that free up the memory or do you have to call Array.Clear ?
@CodeBlend: Neither. You don't set an array to null - you set a variable to null. When there are no live references to the array, it will be eligible for garbage collection (but won't be immediately GC'd). If there are elements within that array which are only referred to by that array, they're eligible for garbage collection too.
9
Array.Clear(theArray, 0, theArray.Length);

1 Comment

That won't compile - Clear isn't an instance method, and it isn't parameterless either.
2

It depends on circumstance (like: what is in the array) but the best method usually is to create a new one. Dropping all references to the old one.

 MyType[] array = ...
 ....

 array = new MyType[size];

Comments

2

I think you can also get away with this for example: SearchTerm = new string[]{};

Comments

0

You can try this.

result = result.Where(x => !string.IsNullOrEmpty(x)).ToArray();

Comments

0

Intellicode showed me to use

aStringArray = Array.Empty<string>();

Comments

-2

string[] foo;

foo = string[""];

Comments

-2

how about

string[] foo;
foo = null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.