Late update : starting with C # 6.0, the zero propagation operator can be used to summarize as follows:
if ( list?.Count > 0 )
or, as a more understandable and more general alternative for IEnumerable<T> :
if ( enumerable?.Any() ?? false )
Note 1: all the top options actually reflect IsNotNullOrEmpty , unlike the OP question ( quote ):
Due to the priority of the IsNullOrEmpty operator IsNullOrEmpty equivalents look less attractive:
if (!(list?.Count > 0))
Note 2: ?? false ?? false necessary for the following reason (resume / quote from this post ):
The operator ?. will return null if the child is null . But [...] if we try to get a non- Nullable member, for example, the Any() method, which returns the bool [...] compiler to "wrap" the return value in Nullable<> . For example, Object?.Any() will give us a bool? (i.e. Nullable<bool> ), not bool . [...] Since it cannot be implicitly cast to bool , this expression cannot be used in if
Note 3: as a bonus, the expression is also βthread-orientedβ (quote from the answer to this question ):
In a multi-threaded context, if [enumerable] is accessible from another thread (either because it is a field that is accessible or because it is closed in a lambda that is exposed to another thread), then the value may differ each time it is calculated [t. e .prior null-check]
Teodor Tite Jan 31 '17 at 14:05 2017-01-31 14:05
source share