tags:

views:

121

answers:

1

I have an array of ints. They start out with 0, then they get filled with some values. Then I want to set all the values back to 0 so that I can use it again, or else just delete the whole array so that I can redeclare it and start with an array of all 0s.

+10  A: 

You can call Array.Clear:

int[] x = new int[10];
for (int i = 0; i < 10; i++)
{
    x[i] = 5;
}
Array.Clear(x, 0, x.Length);

Alternatively, depending on the situation, you may find it clearer to just create a new array instead. In particular, you then don't need to worry about whether some other code still has a reference to the array and expects the old values to be there.

I can't recall ever calling Array.Clear in my own code - it's just not something I've needed.

(Of course, if you're about to replace all the values anyway, you can do that without clearing the array first.)

Jon Skeet