Check for null in foreach loop

前端 未结 7 1641
小鲜肉
小鲜肉 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:51

    Assuming that the type of elements in file.Headers is T you could do this

    foreach(var header in file.Headers ?? Enumerable.Empty<T>()){
      //do stuff
    }
    

    this will create an empty enumerable of T if file.Headers is null. If the type of file is a type you own I would, however, consider changing the getter of Headers instead. null is the value of unknown so if possible instead of using null as "I know there are no elements" when null actually(/originally) should be interpreted as "I don't know if there are any elements" use an empty set to show that you know there are no elements in the set. That would also be DRY'er since you won't have to do the null check as often.

    EDIT as a follow up on Jons suggestion, you could also create an extension method changing the above code to

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

    In the case where you can't change the getter, this would be my own preferred since it expresses the intention more clearly by giving the operation a name (OrEmptyIfNull)

    The extension method mentioned above might make certain optimizations impossible for the optimizer to detect. Specifically, those that are related to IList using method overloading this can be eliminated

    public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
    {
        return source ?? Array.Empty<T>();
    }
    
    0 讨论(0)
提交回复
热议问题