What is the Array.Clear() method in C#?
Overview
In C#, the Array.clear() method is used to clear the contents of an array. For this method, we only need to specify the array, the index position to start the clearing at, and the number of items that need to be cleared.
Syntax
public static void Clear (Array array, int index, int length);
Parameter values
array: This is the array we want to clear.
index: This is the index position of the element from which we need to start the clearance.
length: This is the number of elements that we need to delete from the array array.
Return value
The Array.clear() method returns a new array with some elements removed, based on the parameters that are passed to it.
Note: The removed element is replaced by the default value of that element’s type.
Example
// use Systemusing System;// create classpublic class ArrayClearance {// Main Methodpublic static void Main(){// Creating and initializing the arraydouble[] myArr = {10, 20, 30, 40};Console.WriteLine("Array Before Clearing:");for(int i = 0; i < myArr.Length ; i++){Console.WriteLine(myArr[i]);}// clear arrayArray.Clear(myArr, 1, 3);// Display the values of myArrConsole.WriteLine("Array After Clearing:");for(int i = 0; i < myArr.Length ; i++){Console.WriteLine(myArr[i]);}}}
Explanation
- Line 9: We create an array called
myArr. - Line 11: We use a
forloop to print the elements ofmyArrbefore clearing its elements. - Line 15: We clear some of the elements of the array. We specify that the clearing begins from the element at index position 1 and that only three elements should be cleared.