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

后端 未结 12 1875
旧时难觅i
旧时难觅i 2020-12-07 14:28

I often come across code like the following:

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

Basically, the

12条回答
  •  鱼传尺愫
    2020-12-07 15:08

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

提交回复
热议问题