#598 – Clearing an Array or a Subset of an Array

You can clear (zero out) an array or a subset of an array with a call to the static Array.Clear method.  You pass the array into the method, as well as an indication of what portion of the array you want to clear.

Dog kirby = new Dog("Kirby", 15);
string[] someToys = kirby.FavoriteToys();
int[] someNumbers = kirby.FavoriteNumbers();

DumpArrayContents(someToys, someNumbers);

// Now clear each array
Array.Clear(someToys, 0, someToys.Length);  // Clear entire array
Array.Clear(someNumbers, 1, 2);   // Clear 2nd/3rd elements
DumpArrayContents(someToys, someNumbers);

Notice that after we call Clear on the array of string elements, each element becomes an empty string.  For the array of int values, the two elements that we cleared become zero.

If you call Array.Clear on an array contained reference-typed objects, the values that are cleared become null.

Dog[] pack = { new Dog("Kirby", 15), new Dog("Jack", 17), new Dog("Ruby", 1) };


Array.Clear(pack, 0, pack.Length);