C# .Any() and null values

Words
161
Reading
1 min
Listen
Play
8y

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.

C# .Any() and null values | Ecency