The Array.Clear() method in C# is used to clear the elements in an array and set them to its default. The elements are cleared in a range. The syntax is as follows −
Syntax
public static void Clear (Array arr, int index, int len);
Here, arr is the array whose elements are to be cleared, the index is the beginning index of the elements to clear, and len is the count of elements to clear.
Let us now see an example to implement the Array.Clear() method −
Example
using System;
public class Demo{
public static void Main(){
Console.WriteLine("Array elements...");
int[] arr = { 20, 50, 100, 150, 200, 300, 400, 450, 500, 600, 800, 1000, 1500, 2000 };
for (int i = 0; i < 14; i++){
Console.Write("{0} ", arr[i]);
}
Console.WriteLine();
Console.WriteLine("Clearing some elements in a range...");
Array.Clear(arr, 5, 9);
for (int i = 0; i < 14; i++){
Console.Write("{0} ", arr[i]);
}
Console.WriteLine();
}
}Output
This will produce the following output −
Array elements... 20 50 100 150 200 300 400 450 500 600 800 1000 1500 2000 Clearing some elements in a range... 20 50 100 150 200 0 0 0 0 0 0 0 0 0
Let us see another example −
Example
using System;
public class Demo{
public static void Main(){
Console.WriteLine("Array elements...");
int[,] arr = { {20, 50, 100, 120}, {150, 200, 300, 350}, {400, 450, 500, 550}, {600, 800, 1000, 1200} };
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
Console.Write("{0} ", arr[i,j]);
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("Clearing some elements in a range...");
Array.Clear(arr, 5, 9);
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
Console.Write("{0} ", arr[i,j]);
}
Console.WriteLine();
}
Console.WriteLine();
}
}Output
This will produce the following output −
Array elements... 20 50 100 120 150 200 300 350 400 450 500 550 600 800 1000 1200 Clearing some elements in a range... 20 50 100 120 150 0 0 0 0 0 0 0 0 0 1000 1200