C# Array - Clear() Method



The C# Array Clear() method is used to set a range of element in an array to the default value of each element type. To see the article on this method click here.

Exception

There are the following exceptions ofClear()methods −

  • ArgumentNullException: If array is null.
  • IndexOutOfRangeException: If the index is less than the lower bound of the array, if the length is less than 0, or if the sum of the index and length exceeds the size of the array, then it occurs.

Syntax

Following is the syntax of the C# Array Clear() method −

public static void Clear (Array array, int index, int length);

Parameters

This method accepts the following array −

  • Array: The array whose elements need to be cleared.
  • Index: The starting index of the range of element to clear.
  • Length: The number of element to clear.

Return value

This method does not return any value.

Example 1: Replace with default Value

Let us crate a basic example of the clear() method to replace the element in the range with the default value 0 −

using System;
class Program {
   static void Main() {
      int[] numbers = { 1, 2, 3, 4, 5 };
      Array.Clear(numbers, 1, 3);
      Console.WriteLine(string.Join(", ", numbers));
   }
}

Output

Following is the output −

1, 0, 0, 0, 5

Example 2: Replace with null Value

Let us see another example of the clear() method to clearing the range in string array −

using System;
class Program {
   static void Main() {
      string[] words = { "apple", "banana", "cherry", "date", "elderberry" };
      Array.Clear(words, 2, 2);
      Console.WriteLine(string.Join(", ", words));
   }
}

Output

Following is the output −

apple, banana, , , elderberry

Example 3: Clearing an Entire Boolean Array

This is another, example of theclear()method. The entire array is cleared by specifying index = 0 and length = flags.Length −

using System;
class Program {
   static void Main() {
      bool[] flags = { true, false, true, true, false };
      Array.Clear(flags, 0, flags.Length);
      Console.WriteLine(string.Join(", ", flags));
   }
}

Output

Following is the output −

False, False, False, False, False

Example 4: Clearing a Subset of a Multi-Dimensional Array

The below example, usesthe Clearmethod to treat the array as a flat structure, clearing elements at indices 3, 4, and 5 −

using System;
class Program {
   static void Main() {
      int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
      Array.Clear(matrix, 3, 3);
      foreach (int value in matrix) {
         Console.Write(value + " ");          
      }
   }
}

Output

Following is the output −

1 2 3 0 0 0 7 8 9
csharp_array_class.htm
Advertisements