Checking for empty or null List<string>

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, using ? (Null-conditional) operator (C# 6.0):

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

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
}

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.

Tags:

C#

List