The Array.Clear() method in C# is used to reset one or more elements of an array to their default values. It modifies the existing array without changing its size.
- Numeric elements are reset to
0. boolelements are reset tofalse.- Reference-type elements such as
stringare reset tonull.
using System;
class GFG{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
Array.Clear(numbers, 1, 3);
Console.WriteLine("Array after clearing:");
foreach (int number in numbers)
{
Console.Write(number + " ");
}
}
}
Output
Array after clearing: 10 0 0 0 50
Syntax
Array.Clear(array, index, length);
Parameters
The Array.Clear() method accepts three parameters that specify the array and the range of elements to clear.
array: The array whose elements need to be cleared.index: The starting index from which elements are cleared.length: The number of elements to clear.
How Array.Clear() Works
Array.Clear() resets a specified range of elements instead of removing them from the array. The range is determined by the index and length parameters.
Example
int[] numbers = { 10, 20, 30, 40, 50 };
Array.Clear(numbers, 1, 3);
Here, clearing starts at index 1 and continues for 3 elements. Therefore, the values at indexes 1, 2, and 3 are reset to 0.
The resulting array is: 10 0 0 0 50
Example: Clearing Elements from a String Array
using System;
class Program
{
static void Main()
{
string[] names = { "John", "Alice", "Bob", "David" };
Array.Clear(names, 1, 2);
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
Output
John David
Explanation:
The array contains four string elements.- Array.Clear(names, 1, 2) starts at index 1 and clears two elements.
- "Alice" and "Bob" are reset to null.
- "John" and "David" remain unchanged.
- Console.WriteLine() displays an empty line for the null elements
Default Values After Clearing
The values assigned by Array.Clear() depend on the element type.
int->0double->0bool->falsechar->'\0'- Reference types such as
string->null
Exceptions
Array.Clear() can throw exceptions when the specified array, index, or length is invalid. The main exceptions are
ArgumentNullException: Thrown when the specified array isnull.ArgumentOutOfRangeException: Thrown whenindexorlengthis negative.ArgumentException: Thrown when the specified range extends beyond the bounds of the array.
Reference: