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

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

    Using C# 6 you could use the new null conditional operator together with List<T>.ForEach(Action<T>) (or your own IEnumerable<T>.ForEach extension method).

    List<string> items = null;
    items?.ForEach(item =>
    {
        // ...
    });
    
    0 讨论(0)
  • 2020-12-07 15:11

    As mentioned here you need to check is it not null.

    Do not use an expression that evaluates to null.

    0 讨论(0)
  • 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<T>(this IEnumerable<T> self, Action<T> 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);
    
    0 讨论(0)
  • 2020-12-07 15:13

    It is not superflous. At runtime items will be casted to an IEnumerable and its GetEnumerator method will be called. That will cause a dereferencing of items that will fail

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 15:14

    In C# 6 you can write sth like this:

    // some string from file or UI, i.e.:
    // a) string s = "Hello, World!";
    // b) string s = "";
    // ...
    var items = s?.Split(new char[] { ',', '!', ' ' }) ?? Enumerable.Empty<string>();  
    foreach (var item in items)
    {
        //..
    }
    

    It's basically Vlad Bezden's solution but using the ?? expression to always generate an array that is not null and therefore survives the foreach rather than having this check inside the foreach bracket.

    0 讨论(0)
提交回复
热议问题