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

后端 未结 12 1894
旧时难觅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:14

    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.

提交回复
热议问题