#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) };

DumpArrayContents(pack);

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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: