C# .Any() and null values

in #programming6 years ago (edited)

I was in C# fuckery land today. Not a good place to be. And I place the blame squarely on the Any() function. 

Any() is supposed to to the following.

 Determines whether any element of a sequence exists or satisfies a condition. 

So you'd think that if the value was null it would be ok with that. WRONG! Any() is very much not OK with this. In fact it throws a NullException!

 System.ArgumentNullException: Value cannot be null. Parameter name: source at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source)  

However there is hope. Using some C# magic. 

Consider the following.

List<string> foo = null;
if (foo.Any()) {
   DoStuff();
}

The above will just error out because Any() can't handle a null value. But if we add a few ??? to the if statement. It will then properly process the if statement and handle the null values.

List<string> foo = null;
if (foo?.Any() ?? false) {
   DoStuff();
}


A big thanks to some of the guru's on StackOverflow.

Sort:  

Congratulations @grey580! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

Award for the number of comments received

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

SteemitBoard - Witness Update

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @grey580! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Support SteemitBoard's project! Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63179.13
ETH 2573.33
USDT 1.00
SBD 2.72