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

C#IteratorForeachIteration

C# Problem Overview


I often come across code like the following:

if ( items != null)
{
   foreach(T item in items)
   {
        //...
   }
}

Basically, the if condition ensures that foreach block will execute only if items is not null. I'm wondering if the if condition is really needed, or foreach will handle the case if items == null.

I mean, can I simply write

foreach(T item in items)
{
    //...
}

without worrying about whether items is null or not? Is the if condition superfluous? Or this depends on the type of items or maybe on T as well?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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 =>
{
    // ...
});

Solution 3 - C#

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.

Solution 4 - C#

Actually there is a feature request on that here: https://github.com/dotnet/csharplang/discussions/1081#issuecomment-443209795 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.

Solution 5 - C#

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.

Solution 6 - C#

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

Solution 7 - C#

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

Solution 8 - C#

You do need this. You'll get an exception when foreach accesses the container to set up the iteration otherwise.

Under the covers, foreach uses an interface implemented on the collection class to perform the iteration. The generic equivalent interface is here.

> The foreach statement of the C# > language (for each in Visual Basic) > hides the complexity of the > enumerators. Therefore, using foreach > is recommended instead of directly > manipulating the enumerator.

Solution 9 - C#

The test is necessary, because if the collection is null, foreach will throw a NullReferenceException. It's actually quite simple to try it out.

List<string> items = null;
foreach(var item in items)
{
   Console.WriteLine(item);
}

Solution 10 - C#

the second will throw a NullReferenceException with the message Object reference not set to an instance of an object.

Solution 11 - C#

As mentioned here you need to check is it not null.

>Do not use an expression that evaluates to null.

Solution 12 - C#

In C# 6 you can write sth like this:

// some string from file or UI, i.e.:
// a) string s = "Hello, World!";
// b) string s = "";
// ...
var items = s?.Split(new char[] { ',', '!', ' ' }) ?? Enumerable.Empty<string>();  
foreach (var item in items)
{
    //..
}

It's basically Vlad Bezden's solution but using the ?? expression to always generate an array that is not null and therefore survives the foreach rather than having this check inside the foreach bracket.

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
QuestionNawazView Question on Stackoverflow
Solution 1 - C#Vlad BezdenView Answer on Stackoverflow
Solution 2 - C#kjbartelView Answer on Stackoverflow
Solution 3 - C#Eric LippertView Answer on Stackoverflow
Solution 4 - C#Teoman SoygulView Answer on Stackoverflow
Solution 5 - C#nbzView Answer on Stackoverflow
Solution 6 - C#bocaView Answer on Stackoverflow
Solution 7 - C#JordãoView Answer on Stackoverflow
Solution 8 - C#Steve TownsendView Answer on Stackoverflow
Solution 9 - C#Marius BancilaView Answer on Stackoverflow
Solution 10 - C#harryoversView Answer on Stackoverflow
Solution 11 - C#Renatas M.View Answer on Stackoverflow
Solution 12 - C#dr. rAIView Answer on Stackoverflow