Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is if(items != null) superfluous before foreach(T item in items)?

People also ask

Does for each loop check for NULL?

The question checks if the collection is null first before doing the for-each. Your link checks if the item in the collection is null.

Can we put condition in foreach?

No, a foreach simply works for each element.

Is for faster than foreach?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


You still need to check if (items != null) otherwise you will get NullReferenceException. However you can do something like this:

List<string> items = null;  
foreach (var item in items ?? new List<string>())
{
    item.Dump();
}

but you might check performance of it. So I still prefer having if (items != null) first.

Based on Eric's Lippert suggestion I changed code to:

List<string> items = null;  
foreach (var item in items ?? Enumerable.Empty<string>())
{
    item.Dump();
}

Using C# 6 you could use the new null conditional operator together with List<T>.ForEach(Action<T>) (or your own IEnumerable<T>.ForEach extension method).

List<string> items = null;
items?.ForEach(item =>
{
    // ...
});

The real takeaway here should be a sequence should almost never be null in the first place. Simply make it an invariant in all of your programs that if you have a sequence, it is never null. It is always initialized to be the empty sequence or some other genuine sequence.

If a sequence is never null then obviously you don't need to check it.


Actually there is a feature request on that @Connect: http://connect.microsoft.com/VisualStudio/feedback/details/93497/foreach-should-check-for-null

And the response is quite logical:

I think that most foreach loops are written with the intent of iterating a non-null collection. If you try iterating through null you should get your exception, so that you can fix your code.


You could always test it out with a null list... but this is what I found on the msdn website

foreach-statement:
    foreach   (   type   identifier   in   expression   )   embedded-statement 

If expression has the value null, a System.NullReferenceException is thrown.


It is not superflous. At runtime items will be casted to an IEnumerable and its GetEnumerator method will be called. That will cause a dereferencing of items that will fail


You can encapsulate the null check in an extension method and use a lambda:

public static class EnumerableExtensions {
  public static void ForEach<T>(this IEnumerable<T> self, Action<T> action) {
    if (self != null) {
      foreach (var element in self) {
        action(element);
      }
    }
  }
}

The code becomes:

items.ForEach(item => { 
  ...
});

If can be even more concise if you want to just call a method that takes an item and returns void:

items.ForEach(MethodThatTakesAnItem);