[c#] Checking for empty or null List<string>

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"

This question is related to c# list

The answer is


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.


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.


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;
}

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");

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 
}

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.


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.


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

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.


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())
{
    ....
}

Try and use:

if(myList.Any())
{

}

Note: this assmumes myList is not null.


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

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


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

}`


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;
}

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
}

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;
}

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))

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
}