The Array
class in the System
namespace provides the Clear()
method, which sets a range of array elements to their default value in C#.
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.
Clear()
method resets the elements to their default type value. All null
. All value types are set to their known default value, such as Boolean to false, integers to 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 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));}}