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 Array that needs to be cleared, the starting index of the range of elements, and the number of elements to clear as inputs to the function.

  • It throws an exception if the input array is null, if the index is less than the lower bound of the array, or if the sum of index and length is greater than the array’s length.

Things to note

  • The Clear() method resets the elements to their default type value. All reference types valuese.g., string, object, interface are set to null. All value types are set to their known default value, such as Boolean to false, integers to 0zero, etc. It does not delete the element, but only resets the value to the type’s default value.
  • 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 0zero for integers, and set to false for 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));
}
}

Free Resources