Check for null in foreach loop

前端 未结 7 1683
小鲜肉
小鲜肉 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 collection = new List();
    collection = null;
    foreach (var i in collection ?? Enumerable.Empty())
    {
        //your code here
    }
    

    (replace the collection with your true object/type)

提交回复
热议问题