How to set array elements to their default value in C#
The Array class in the System namespace provides the Clear() method, which sets a range of array elements to their default value in C#.
Syntax
public static void Clear (Array array, int index, int length);
-
It takes the
Arraythat needs to be cleared, the startingindexof the range of elements, and thenumber of elementsto clear as inputs to the function. -
It throws an exception if the input array is
null, if theindexis less than the lower bound of the array, or if the sum ofindexandlengthis greater than the array’s length.
Things to note
- The
Clear()method resets the elements to their default type value. All are set toreference types values e.g., string, object, interface null. All value types are set to their known default value, such as Boolean to false, integers to , etc. It does not delete the element, but only resets the value to the type’s default value.0 zero - This is an O(n) operation.
Code
In the code below, we have created an integer array and a Boolean array, then used the Array. The Clear() method sets the range of values passed as input to their default values. The array elements are printed before and after the Clear() operation.
Notice that in the output below, the values are set to
for integers, and set to 0 zero falsefor the Boolean array for the specified range in the array.
using System;class HelloWorld{static void Main(){int[] integerArray = {12,34,34,44};Console.WriteLine("Integer Array Before Clear()");Console.WriteLine("{0}", string.Join(",",integerArray));Array.Clear(integerArray, 0,3);Console.WriteLine("Integer Array After Clear()");Console.WriteLine("{0}", string.Join(",",integerArray));bool[] boolArray = {true, true, true, true, true};Console.WriteLine("Boolean Array Before Clear()");Console.WriteLine("{0}", string.Join(",",boolArray));Array.Clear(boolArray, 2,2);Console.WriteLine("Boolean Array After Clear()");Console.WriteLine("{0}", string.Join(",",boolArray));}}