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

Nawaz picture Nawaz · Jun 23, 2011 · Viewed 58.3k times · Source

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?

Answer

Vlad Bezden picture Vlad Bezden · Jun 23, 2011

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