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"
isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
An empty collection isn't the same as null . An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.
Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.
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"); }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With