Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Remove all elements from the ArrayList in C#
To remove all elements from an ArrayList in C#, you can use the Clear() method. This method removes all elements from the ArrayList and sets the Count property to zero.
Syntax
Following is the syntax for the Clear() method −
arrayList.Clear();
Parameters
The Clear() method does not take any parameters.
Return Value
The Clear() method does not return any value. It is a void method that modifies the ArrayList in-place.
Using Clear() to Remove All Elements
The following example demonstrates how to use the Clear() method to remove all elements from an ArrayList −
using System;
using System.Collections;
public class Demo {
public static void Main(string[] args) {
ArrayList arrList = new ArrayList();
arrList.Add("One");
arrList.Add("Two");
arrList.Add("Three");
arrList.Add("Four");
arrList.Add("Five");
Console.WriteLine("Elements in ArrayList...");
foreach (string res in arrList) {
Console.WriteLine(res);
}
Console.WriteLine("Count of elements in ArrayList = " + arrList.Count);
arrList.Clear();
Console.WriteLine("Count of elements in ArrayList (After Clear) = " + arrList.Count);
}
}
The output of the above code is −
Elements in ArrayList... One Two Three Four Five Count of elements in ArrayList = 5 Count of elements in ArrayList (After Clear) = 0
Clear() vs Reference Assignment
The following example shows the difference between Clear() method and reference assignment when multiple variables reference the same ArrayList −
using System;
using System.Collections;
public class Demo {
public static void Main(string[] args) {
ArrayList list1 = new ArrayList();
list1.Add("A");
list1.Add("B");
list1.Add("C");
ArrayList list2 = list1; // Both reference same ArrayList
Console.WriteLine("Before Clear:");
Console.WriteLine("List1 Count = " + list1.Count);
Console.WriteLine("List2 Count = " + list2.Count);
Console.WriteLine("Are they the same object? " + ReferenceEquals(list1, list2));
list1.Clear(); // Clears the ArrayList that both variables reference
Console.WriteLine("\nAfter Clear:");
Console.WriteLine("List1 Count = " + list1.Count);
Console.WriteLine("List2 Count = " + list2.Count);
}
}
The output of the above code is −
Before Clear: List1 Count = 3 List2 Count = 3 Are they the same object? True After Clear: List1 Count = 0 List2 Count = 0
Conclusion
The Clear() method is the most efficient way to remove all elements from an ArrayList in C#. It instantly removes all elements and resets the Count to zero, making it useful when you need to reuse an existing ArrayList without creating a new instance.
