Checking for empty or null List<string>

C#List

C# Problem Overview


I have a List where sometimes it is empty or null. I want to be able to check if it contains any List-item and if not then add an object to the List.

 // I have a list, sometimes it doesn't have any data added to it
    var myList = new List<object>(); 
 // Expression is always false
    if (myList == null) 
        Console.WriteLine("List is never null"); 
    if (myList[0] == null) 
        myList.Add("new item"); 
    //Errors encountered:  Index was out of range. Must be non-negative and less than the size of the collection.
    // Inner Exception says "null"

C# Solutions


Solution 1 - C#

Try the following code:

 if ( (myList!= null) && (!myList.Any()) )
 {
     // Add new item
     myList.Add("new item"); 
 }

A late EDIT because for these checks I now like to use the following solution. First, add a small reusable extension method called Safe():

public static class IEnumerableExtension
{       
    public static IEnumerable<T> Safe<T>(this IEnumerable<T> source)
    {
        if (source == null)
        {
            yield break;
        }

        foreach (var item in source)
        {
            yield return item;
        }
    }
}

And then, you can do the same like:

 if (!myList.Safe().Any())
 {
      // Add new item
      myList.Add("new item"); 
 }

I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.

And another EDIT, which doesn't require an extension method, but uses the ? (Null-conditional) operator (C# 6.0):

if (!(myList?.Any() ?? false))
{
    // Add new item
    myList.Add("new item"); 
}

Solution 2 - C#

For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:

if (list?.Any() != true)
{
    // Handle null or empty list
}

Solution 3 - C#

Checkout L-Four's answer.

A less-efficient answer:

if(myList.Count == 0){
    // nothing is there. Add here
}

Basically new List<T> will not be null but will have no elements. As is noted in the comments, the above will throw an exception if the list is uninstantiated. But as for the snippet in the question, where it is instantiated, the above will work just fine.

If you need to check for null, then it would be:

if(myList != null && myList.Count == 0){
  // The list is empty. Add something here
}

Even better would be to use !myList.Any() and as is mentioned in the aforementioned L-Four's answer as short circuiting is faster than linear counting of the elements in the list.

Solution 4 - C#

What about using an extension method?

public static bool AnyOrNotNull<T>(this IEnumerable<T> source)
{
  if (source != null && source.Any())
    return true;
  else
    return false;
}

Solution 5 - C#

An easy way to combine myList == null || myList.Count == 0 would be to use the null coalescing operator ??:

if ((myList?.Count ?? 0) == 0) {
    //My list is null or empty
}

Solution 6 - C#

if (myList?.Any() == true) 
{
   ...
}

I find this the most convenient way. '== true' checks the value of the nullable bool implied by '?.Any()

Solution 7 - C#

Assuming that the list is never null, the following code checks if the list is empty and adds a new element if empty:

if (!myList.Any())
{
    myList.Add("new item");
}

If it is possible that the list is null, a null check must be added before the Any() condition:

if (myList != null && !myList.Any())
{
    myList.Add("new item");
}

In my opinion, using Any() instead of Count == 0 is preferable since it better expresses the intent of checking if the list has any element or is empty. However, considering the performance of each approach, using Any() is generally slower than Count.

Solution 8 - C#

I was wondering nobody suggested to create own extension method more readable name for OP's case.

public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
    if (source == null)
    {
        return true;
    }

    return source.Any() == false;
}

Solution 9 - C#

myList[0] gets the first item in the list. Since the list is empty there is no item to get and you get the IndexOutOfRangeException instead.

As other answers here have shown, in order to check if the list is empty you need to get the number of elements in the list (myList.Count) or use the LINQ method .Any() which will return true if there are any elements in the list.

Solution 10 - C#

Your List has no items, that's why access to non-existing 0th item

myList[0] == null

throws Index was out of range exception; when you want to access n-th item check

  if (myList.Count > n)
    DoSomething(myList[n])

in your case

  if (myList.Count > 0) // <- You can safely get 0-th item
    if (myList[0] == null) 
      myList.Add("new item");

Solution 11 - C#

Most answers here focused on how to check if a collection is Empty or Null which was quite straight forward as demonstrated by them.

Like many people here, I was also wondering why does not Microsoft itself provide such a basic feature which is already provided for String type (String.IsNullOrEmpty())? Then I encountered this guideline from Microsoft where it says:

> X DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead. > > The general rule is that null and empty (0 item) collections or arrays > should be treated the same.

So, ideally you should never have a collection which is null if you follow this guideline from Microsoft. And that will help you to remove unnecessary null checking which ultimately will make your code more readable. In this case, someone just need to check : myList.Any() to find out whether there is any element present in the list.

Hope this explanation will help someone who will face same problem in future and wondering why isn't there any such feature to check whether a collection is null or empty.

Solution 12 - C#

List in c# has a Count property. It can be used like so:

if(myList == null) // Checks if list is null
    // Wasn't initialized
else if(myList.Count == 0) // Checks if the list is empty
    myList.Add("new item");
else // List is valid and has something in it
    // You could access the element in the list if you wanted

Solution 13 - C#

If you want a single line condition that checks both null and empty, you can use

if (list == null ? true : (!list.Any()))

This will work in older framework versions where the null-conditional operator is not available.

Solution 14 - C#

You can check the list is empty or not in multiple ways

1)Checklist is null and then check count is greater than zero like below:-

if (myList != null && myList.Count > 0)
{
	//List has more than one record.
}

2)Checklist null and count greater than zero using LINQ query like below:-

if (myList?.Any() == true)
{
	//List has more than one record.
}

Solution 15 - C#

Try and use:

if(myList.Any())
{

}

Note: this assmumes myList is not null.

Solution 16 - C#

You can use Count property of List in c#

please find below code which checks list empty and null both in a single condition

if(myList == null || myList.Count == 0)
{
    //Do Something 
}

Solution 17 - C#

The IsNullOrEmpty() extension method is a very elegant and human-readable way of implementing this, so I decided to use it. However, you can achieve the same thing without extension methods, too.

Let's say we have an object named list of type List<T> (e.g. List<string>). If you want to know whether the list has items, you can say:

list?.Count > 0 // List<T> has items

This will return false for an empty list and also if the list itself is a null object, true otherwise.

So the only thing you need to do if you want to check whether the list doesn't have any items is to invert the above expression:

!(list?.Count > 0) // List<T> is null or empty

This will return true for an empty list and also if the list itself is a null object, false otherwise. Exactly what you expect from an IsNullOrEmpty evaluation. Just a little cryptic!

As List<T> implements IEnumerable<T>, you can implement the same thing less specific, but this will possibly make the evaluation slower:

list?.Any() != true // IEnumerable<T> is null or empty

Solution 18 - C#

We can validate like below with Extension methods. I use them for all of my projects.

  var myList = new List<string>();
  if(!myList.HasValue())
  {
	 Console.WriteLine("List has value(s)");			  
  }
  
  if(!myList.HasValue())
  {
	 Console.WriteLine("List is either null or empty");			  
  }
  
  if(myList.HasValue())
  {
	  if (!myList[0].HasValue()) 
	  {
		  myList.Add("new item"); 
	  }
  }
      	  
	      	  


/// <summary>
/// This Method will return True if List is Not Null and it's items count>0       
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns>Bool</returns>
public static bool HasValue<T>(this IEnumerable<T> items)
{
	if (items != null)
	{
		if (items.Count() > 0)
		{
			return true;
		}
	}
	return false;
}

		
/// <summary>
/// This Method will return True if List is Not Null and it's items count>0       
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns></returns>
public static bool HasValue<T>(this List<T> items)
{
	if (items != null)
	{
		if (items.Count() > 0)
		{
			return true;
		}
	}
	return false;
}


/// <summary>
///  This method returns true if string not null and not empty  
/// </summary>
/// <param name="ObjectValue"></param>
/// <returns>bool</returns>
public static bool HasValue(this string ObjectValue)
{
	if (ObjectValue != null)
	{
		if ((!string.IsNullOrEmpty(ObjectValue)) && (!string.IsNullOrWhiteSpace(ObjectValue)))
		{
			return true;
		}
	}
	return false;
}

          

Solution 19 - C#

We can add an extension to create an empty list

    public static IEnumerable<T> Nullable<T>(this IEnumerable<T> obj)
    {
        if (obj == null)
            return new List<T>();
        else
            return obj;
    }

And use like this

foreach (model in models.Nullable())
{
    ....
}

Solution 20 - C#

I personally create an extension method for the IEnumerable class which I call IsNullOrEmpty(). Because it applies to all implementations of IEnumerable, it works for a List, but also for a String, IReadOnlyList, etc.

My implementation is simply this:

public static class ExtensionMethods
{
    public static bool IsNullOrEmpty(this IEnumerable enumerable)
    {
        if (enumerable is null) return true;

        foreach (var element in enumerable)
        {
            //If we make it here, it means there are elements, and we return false
            return false;
        }

        return true;
    }
}

I can then use the method on a list as follows:

var myList = new List<object>();

if (myList.IsNullOrEmpty())
{
    //Do stuff
}

Solution 21 - C#

I just wanted to add an answer here since this is the top hit on Google for checking if a List is null or empty. For me .Any is not recognized. If you want to check without creating an extension method you can do it like this which is pretty simple:

//Check that list is NOT null or empty.
if (myList != null && myList.Count > 0)
{
    //then proceed to do something, no issues here.
}

//Check if list is null or empty.
if (myList == null || myList.Count == 0)
{
    //error handling here for null or empty list
}

//checking with if/else-if/else
if (myList == null)
{
    //null handling
}
else if(myList.Count == 0)
{
    //handle zero count
}
else
{
    //no issues here, proceed
}

If there is a possibility the list could be null then you must check for null first - if you try to check the count first and the list happens to be null then it will throw an error. && and || are short-circuit operators, so the second condition is only evaluated if the first is not satisfied.

Solution 22 - C#

You can add this IEnumerable extension method that returns true if the source sequence either contains any elements and is not null. Otherwise returns false.

public static class IEnumerableExtensions
{
    public static bool IsNotNullNorEmpty<T>(this IEnumerable<T> source)
       => source?.Any() ?? false;
}

Solution 23 - C#

public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
   return !(items?.Any() ?? false);
}

This extension method helps you determine if a list is either null or empty. It can be used as follows:

using System;
using System.Linq;
using System.Collections.Generic;

public static class IEnumerableExtensions
{
	public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
	{
		return !(items?.Any() ?? false);
	}
}

public class Program
{	
	public static void Main()
	{
		List<string> test1 = null;;
		Console.WriteLine($"List 1 is empty: {test1.IsNullOrEmpty()}");
		//Output: List 1 is empty: True

		var test2 = new System.Collections.Generic.List<string>();
		System.Console.WriteLine($"List 2 is empty: {test2.IsNullOrEmpty()}");
		//Output: List 2 is empty: True

		var test3 = new System.Collections.Generic.List<string>();
		test3.Add("test");
		System.Console.WriteLine($"List 3 is empty: {test3.IsNullOrEmpty()}");
		//Output: List 3 is empty: False
	}
}

Solution 24 - C#

Because you initialize myList with 'new', the list itself will never be null.

But it can be filled with 'null' values.

In that case .Count > 0 and .Any() will be true. You can check this with the .All(s => s == null)

var myList = new List<object>();
if (myList.Any() || myList.All(s => s == null))

Solution 25 - C#

This is able to solve your problem `if(list.Length > 0){

}`

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonathan KittellView Question on Stackoverflow
Solution 1 - C#L-FourView Answer on Stackoverflow
Solution 2 - C#mechView Answer on Stackoverflow
Solution 3 - C#Amit JokiView Answer on Stackoverflow
Solution 4 - C#swissbenView Answer on Stackoverflow
Solution 5 - C#MattkwishView Answer on Stackoverflow
Solution 6 - C#bvh9000View Answer on Stackoverflow
Solution 7 - C#Luca CremonesiView Answer on Stackoverflow
Solution 8 - C#BasinView Answer on Stackoverflow
Solution 9 - C#Andrew CooperView Answer on Stackoverflow
Solution 10 - C#Dmitry BychenkoView Answer on Stackoverflow
Solution 11 - C#Md Hasan IbrahimView Answer on Stackoverflow
Solution 12 - C#Andrew_CSView Answer on Stackoverflow
Solution 13 - C#johnnydangerView Answer on Stackoverflow
Solution 14 - C#Abhay.PatilView Answer on Stackoverflow
Solution 15 - C#Alexandru ChichineteView Answer on Stackoverflow
Solution 16 - C#Niraj TrivediView Answer on Stackoverflow
Solution 17 - C#Kim HomannView Answer on Stackoverflow
Solution 18 - C#AnandhaView Answer on Stackoverflow
Solution 19 - C#Damian HaynesView Answer on Stackoverflow
Solution 20 - C#SugarCodingView Answer on Stackoverflow
Solution 21 - C#SendETHToThisAddressView Answer on Stackoverflow
Solution 22 - C#MikolajView Answer on Stackoverflow
Solution 23 - C#Bart CoppensView Answer on Stackoverflow
Solution 24 - C#TessaView Answer on Stackoverflow
Solution 25 - C#user14525780View Answer on Stackoverflow