How to empty a C# list?


To empty a C# list, use the Clear() method.

Firstly, set a list and add elements −

List<string> myList = new List<string>()
{
   "one",
   "two",
   "three",
   "four",
   "five",
   "six"
};

Now, let us empty the list −

myList.Clear();

Example

 Live Demo

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"
      };
      foreach(string str in myList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Elements in the list = "+myList.Count);
      // this makes a list empty
      myList.Clear();
      Console.WriteLine("Elements in the list after using Clear() = "+myList.Count);
   }
}

Output

one
two
three
four
five
six
Elements in the list = 6
Elements in the list after using Clear() = 0

Updated on: 22-Jun-2020

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements