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

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

    You do need this. You'll get an exception when foreach accesses the container to set up the iteration otherwise.

    Under the covers, foreach uses an interface implemented on the collection class to perform the iteration. The generic equivalent interface is here.

    The foreach statement of the C# language (for each in Visual Basic) hides the complexity of the enumerators. Therefore, using foreach is recommended instead of directly manipulating the enumerator.

提交回复
热议问题