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.
1 Answer
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.)
2 Comments
Jeppe Stig Nielsen
Any array also implements the non-generic
IList interface which has a Clear method. Saying ((IList)x).Clear(); also "clears" the array instance, although this is not well documented. If the array is actually one-dimensional and zero-indexed, it also "magically" implements the generic IList<> interface which has another method also called Clear. If you say ((IList<int>)x).Clear(); you get a run-time exception! It is a subtlety that these two explicit interface implementations in Array behave differently.Gyfis
Thank you for the comment about some code having reference to the array! Doing s1 = s2; and Array.Clear(s2, 0, s2.Length), it took me time before realizing what I've done. Thanks!