When calling Any() on a null object, it throws an ArgumentNullException in C#. If the object is null, there definitely aren't 'any', and it should probably return false.
Why does C# behave this way?
Any()
is asking: "Does this box contain any items?"
If the box is empty, the answer is clearly no.
But if there is no box in the first place, then the question makes no sense, and the function complains: "What the hell are you talking about? There is no box."
When I want to treat a missing collection like an empty one, I use the following extension method:
public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> sequence)
{
return sequence ?? Enumerable.Empty<T>();
}
This can be combined with all LINQ methods and foreach
, not just .Any()
.