Does C# have IsNullOrEmpty for List/IEnumerable?

前端 未结 10 536
一生所求
一生所求 2020-12-23 11:04

I know generally empty List is more prefer than NULL. But I am going to return NULL, for mainly two reasons

  1. I have to check and handle null values explicitly,
10条回答
  •  被撕碎了的回忆
    2020-12-23 11:42

    Late update: since C# 6.0, the null-propagation operator may be used to express concise like this:

    if (  list?.Count  > 0 ) // For List
    if ( array?.Length > 0 ) // For Array
    

    or, as a cleaner and more generic alternative for IEnumerable:

    if ( enumerable?.Any() ?? false )
    

    Note 1: all upper variants reflect actually IsNotNullOrEmpty, in contrast to OP question (quote):

    Because of operator precedence IsNullOrEmpty equivalents look less appealing:
    if (!(list?.Count > 0))

    Note 2: ?? false is necessary, because of the following reason (summary/quote from this post):

    ?. operator will return null if a child member is null. But [...] if we try to get a non-Nullable member, like the Any() method, that returns bool [...] the compiler will "wrap" a return value in Nullable<>. For example, Object?.Any() will give us bool? (which is Nullable), not bool. [...] Since it can't be implicitly casted to bool this expression cannot be used in the if

    Note 3: as a bonus, the statement is also "thread-safe" (quote from answer of this question):

    In a multithreaded context, if [enumerable] is accessible from another thread (either because it's a field that's accessible or because it's closed over in a lambda that is exposed to another thread) then the value could be different each time it's computed [i.e.prior null-check]

提交回复
热议问题