Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear an array in Visual C#

Tags:

arrays

c#

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.

like image 630
neuromancer Avatar asked Nov 27 '09 07:11

neuromancer


People also ask

Can you clear an array in C?

Use the memset Function to Clear Char Array in Ch> header file. memset takes three arguments - the first is the void pointer to the memory region, the second argument is the constant byte value, and the last one denotes the number of bytes to be filled at the given memory address.

How do you clear an array in Visual Basic?

You need to use the “Erase” statement to clear an array in VBA. Add the keyword “Erase” before the name of the array that you want to clear but note that all the values will be reset from the array.

How do you clear a string array in C#?

To empty an array in C#, use the Array Clear() method: The Array. Clear method in C# clears i.e.zeros out all elements.

How do you clear a double array in C#?

Just reallocate it. double D[,] = new double[N,M]; creates a empty 2D array.


1 Answers

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.)

like image 187
Jon Skeet Avatar answered Sep 25 '22 11:09

Jon Skeet