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

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

    You can encapsulate the null check in an extension method and use a lambda:

    public static class EnumerableExtensions {
      public static void ForEach(this IEnumerable self, Action action) {
        if (self != null) {
          foreach (var element in self) {
            action(element);
          }
        }
      }
    }
    

    The code becomes:

    items.ForEach(item => { 
      ...
    });
    

    If can be even more concise if you want to just call a method that takes an item and returns void:

    items.ForEach(MethodThatTakesAnItem);
    

提交回复
热议问题