C# program to check whether a list is empty or not

CsharpProgrammingServer Side Programming

Use lists in C# to store elements and fetch it. Let us see an example.

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(string[] args) {
      var subjects = new List<string>();
      subjects.Add("Maths");
      subjects.Add("Java");
      subjects.Add("English");
      subjects.Add("Science");
      subjects.Add("Physics");
      subjects.Add("Chemistry");
      foreach (var sub in subjects) {
         Console.WriteLine(sub);
      }
   }
}

Output

Maths
Java
English
Science
Physics
Chemistry

Now to check whether a list is empty or not, use the Count property.

if (subjects.Count == 0)
Console.WriteLine("List is empty!");

Now let us see the complete code.

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(string[] args) {
      var subjects = new List<string>();
      subjects.Add("Maths");
      subjects.Add("Java");
      subjects.Add("English");
      subjects.Add("Science");
      subjects.Add("Physics");
      subjects.Add("Chemistry");
      if (subjects.Count == 0)
      Console.WriteLine("List is empty!");
      foreach (var sub in subjects) {
         Console.WriteLine(sub);
      }
   }
}

Output

Maths
Java
English
Science
Physics
Chemistry
raja
Published on 18-Sep-2018 08:24:12
Advertisements