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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)