Clear a list in C#

To clear a list in C#, you use the Clear() method which removes all elements from the list. This method is part of the List<T> class and provides an efficient way to empty a list without recreating it.

Syntax

Following is the syntax for the Clear()

listName.Clear();

Parameters

The Clear() method takes no parameters.

Return Value

The Clear() method returns void ? it modifies the existing list by removing all elements.

Using Clear() Method

Example

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      List<int> myList = new List<int>();
      myList.Add(45);
      myList.Add(77);
      myList.Add(23);
      Console.WriteLine("Elements before clear: " + myList.Count);
      
      // Display elements
      Console.Write("List contents: ");
      foreach (int item in myList) {
         Console.Write(item + " ");
      }
      Console.WriteLine();
      
      // Clear the list
      myList.Clear();
      Console.WriteLine("Elements after clear: " + myList.Count);
      Console.WriteLine("List is empty: " + (myList.Count == 0));
   }
}

The output of the above code is −

Elements before clear: 3
List contents: 45 77 23 
Elements after clear: 0
List is empty: True

Clearing Different Types of Lists

Example

using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {
      // String list
      List<string> names = new List<string> {"Alice", "Bob", "Charlie"};
      Console.WriteLine("String list count: " + names.Count);
      names.Clear();
      Console.WriteLine("After clear: " + names.Count);
      
      // Double list
      List<double> prices = new List<double> {10.5, 20.3, 15.7};
      Console.WriteLine("Double list count: " + prices.Count);
      prices.Clear();
      Console.WriteLine("After clear: " + prices.Count);
      
      // Boolean list
      List<bool> flags = new List<bool> {true, false, true};
      Console.WriteLine("Boolean list count: " + flags.Count);
      flags.Clear();
      Console.WriteLine("After clear: " + flags.Count);
   }
}

The output of the above code is −

String list count: 3
After clear: 0
Double list count: 3
After clear: 0
Boolean list count: 3
After clear: 0

Clear() vs Creating New List

Clear() Method New List Creation
Reuses existing list object Creates a new list object
More memory efficient Uses more memory (garbage collection needed)
myList.Clear(); myList = new List<int>();
Preserves list capacity Resets to default capacity

Conclusion

The Clear() method efficiently removes all elements from a List<T> in C#. It's more memory-efficient than creating a new list and works with any generic list type, making it the preferred approach for emptying existing lists.

Updated on: 2026-03-17T07:04:35+05:30

505 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements