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


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

Updated on: 23-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements