Check for null in foreach loop

前端 未结 7 1640
小鲜肉
小鲜肉 2020-11-30 20:57

Is there a nicer way of doing the following:
I need a check for null to happen on file.Headers before proceeding with the loop

if (file.Headers != null         


        
相关标签:
7条回答
  • 2020-11-30 21:25

    the "if" before the iteration is fine, few of those "pretty" semantics can make your code less readable.

    anyway, if the indentation disturbs your, you can change the if to check:

    if(file.Headers == null)  
       return;
    

    and you'll get to the foreach loop only when there is a true value at the headers property.

    another option I can think about is using the null-coalescing operator inside your foreach loop and to completely avoid null checking. sample:

    List<int> collection = new List<int>();
    collection = null;
    foreach (var i in collection ?? Enumerable.Empty<int>())
    {
        //your code here
    }
    

    (replace the collection with your true object/type)

    0 讨论(0)
  • 2020-11-30 21:25

    Using Null-conditional Operator and ForEach() which works faster than standard foreach loop.
    You have to cast the collection to List though.

       listOfItems?.ForEach(item => // ... );
    
    0 讨论(0)
  • 2020-11-30 21:28

    Just as a slight cosmetic addition to Rune's suggestion, you could create your own extension method:

    public static IEnumerable<T> OrEmptyIfNull<T>(this IEnumerable<T> source)
    {
        return source ?? Enumerable.Empty<T>();
    }
    

    Then you can write:

    foreach (var header in file.Headers.OrEmptyIfNull())
    {
    }
    

    Change the name according to taste :)

    0 讨论(0)
  • 2020-11-30 21:29

    Frankly, I advise: just suck up the null test. A null test is just a brfalse or brfalse.s; everything else is going to involve much more work (tests, assignments, extra method calls, unnecessary GetEnumerator(), MoveNext(), Dispose() on the iterator, etc).

    An if test is simple, obvious, and efficient.

    0 讨论(0)
  • 2020-11-30 21:36

    I am using a nice little extension method for these scenarios:

      public static class Extensions
      {
        public static IList<T> EnsureNotNull<T>(this IList<T> list)
        {
          return list ?? new List<T>();
        }
      }
    

    Given that Headers is of type list, you can do following:

    foreach(var h in (file.Headers.EnsureNotNull()))
    {
      //do stuff
    }
    
    0 讨论(0)
  • 2020-11-30 21:42

    For some cases I'd prefer slightly another, generic variant, assuming that, as a rule, default collection constructors return empty instances.

    It would be better to name this method NewIfDefault. It can be useful not only for collections, so type constraint IEnumerable<T> is maybe redundant.

    public static TCollection EmptyIfDefault<TCollection, T>(this TCollection collection)
            where TCollection: class, IEnumerable<T>, new()
        {
            return collection ?? new TCollection();
        }
    
    0 讨论(0)
提交回复
热议问题