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
How to empty a C# list?
To empty a C# list, use the Clear() method. This method removes all elements from the list and sets the count to zero. The Clear() method is the most efficient way to empty a list as it removes all elements in a single operation.
Syntax
Following is the syntax for the Clear() method −
listName.Clear();
Parameters
The Clear() method does not take any parameters.
Return Value
The Clear() method does not return any value. It modifies the list in-place by removing all elements.
Using Clear() Method
The following example demonstrates how to empty a list using the Clear() method −
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List<string> myList = new List<string>() {
"one",
"two",
"three",
"four",
"five",
"six"
};
Console.WriteLine("Original list:");
foreach(string str in myList) {
Console.WriteLine(str);
}
Console.WriteLine("Elements in the list = " + myList.Count);
// Empty the list using Clear()
myList.Clear();
Console.WriteLine("Elements in the list after using Clear() = " + myList.Count);
Console.WriteLine("List is now empty: " + (myList.Count == 0));
}
}
The output of the above code is −
Original list: one two three four five six Elements in the list = 6 Elements in the list after using Clear() = 0 List is now empty: True
Clear() vs Creating a New List
There are two common approaches to empty a list. Here's a comparison between them −
| Method | Performance | Memory Usage |
|---|---|---|
list.Clear() |
Faster - removes elements in place | Maintains existing capacity |
list = new List<T>() |
Slower - creates new object | Creates new list, old one becomes garbage |
Example Comparing Both Approaches
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
// Method 1: Using Clear()
List<int> numbers1 = new List<int> {1, 2, 3, 4, 5};
Console.WriteLine("Before Clear(): Count = " + numbers1.Count);
numbers1.Clear();
Console.WriteLine("After Clear(): Count = " + numbers1.Count);
// Method 2: Creating new list (less efficient)
List<int> numbers2 = new List<int> {10, 20, 30, 40, 50};
Console.WriteLine("Before new assignment: Count = " + numbers2.Count);
numbers2 = new List<int>();
Console.WriteLine("After new assignment: Count = " + numbers2.Count);
}
}
The output of the above code is −
Before Clear(): Count = 5 After Clear(): Count = 0 Before new assignment: Count = 5 After new assignment: Count = 0
Conclusion
The Clear() method is the recommended and most efficient way to empty a C# list. It removes all elements in a single operation while maintaining the list's existing capacity, making it faster than creating a new list instance.
