C# List.Clear() technique: Here, we will find out about the Clear() strategy for List with example.
C# List.Clear() Method
List.Clear() technique is utilized to clear the rundown, it expels all components from the rundown.
Syntax:
void List<T>.Clear();
Parameter: It acknowledges nothing.
Return value: It returns nothing – it’s profits type is void
Example:
int list declaration:
List<int> a = new List<int>();
adding elements:
a.Add(10);
a.Add(20);
a.Add(30);
a.Add(40);
a.Add(50);
removing elements:
a.Clear();
Output:
None
C# Example to expel all things from the rundown utilizing List.Clear() Method
using System;
using System.Text;
using System.Collections.Generic;
namespace Test
{
class Program
{
static void printList(List<int> lst)
{
//printing elements
foreach (int item in lst)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
//integer list
List<int> a = new List<int>();
//adding elements
a.Add(10);
a.Add(20);
a.Add(30);
a.Add(40);
a.Add(50);
if (a.Count > 0)
{
//print the list
Console.WriteLine("list elements...");
printList(a);
}
else
{
Console.WriteLine("list is empty");
}
//clear all elements
a.Clear();
//list after removing the elements
if (a.Count > 0)
{
Console.WriteLine("list elements after removing elements...");
printList(a);
}
else
{
Console.WriteLine("list is empty");
}
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
list elements...
10 20 30 40 50
list is empty