Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
communitycreator

What is the Array.Clear() method in C#?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 System
using System;
// create class
public class ArrayClearance {
// Main Method
public static void Main()
{
// Creating and initializing the array
double[] myArr = {10, 20, 30, 40};
Console.WriteLine("Array Before Clearing:");
for(int i = 0; i < myArr.Length ; i++){
Console.WriteLine(myArr[i]);
}
// clear array
Array.Clear(myArr, 1, 3);
// Display the values of myArr
Console.WriteLine("Array After Clearing:");
for(int i = 0; i < myArr.Length ; i++){
Console.WriteLine(myArr[i]);
}
}
}
Clearing an array in C#

Explanation

  • Line 9: We create an array called myArr.
  • Line 11: We use a for loop to print the elements of myArr before 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.

RELATED TAGS

c#
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring