How to clear an array in Visual C #

I have an array of ints. They begin with 0, then are filled with some values. Then I want to return all the values โ€‹โ€‹back to 0 in order to use it again, or just delete the whole array so that I can update it and start with an array of all 0.

+7
arrays c #
source share
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 easier to create a new array instead. In particular, you don't have to worry about whether any other code has an array reference and expects the old values โ€‹โ€‹to be there.

I canโ€™t remember ever calling Array.Clear in my own code - this is just not what I need.

(Of course, if you replace all the values โ€‹โ€‹anyway, you can do this without clearing the array first).

+28
source share

All Articles