I often come across code like the following:
if ( items != null)
{
foreach(T item in items)
{
//...
}
}
Basically, the
You still need to check if (items != null) otherwise you will get NullReferenceException. However you can do something like this:
List items = null;
foreach (var item in items ?? new List())
{
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 items = null;
foreach (var item in items ?? Enumerable.Empty())
{
item.Dump();
}