Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Any() work on a c# null object

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?

like image 797
DefenestrationDay Avatar asked Jul 18 '12 09:07

DefenestrationDay


People also ask

Does any () check for null C#?

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.

How check double value is null or not in C#?

IsNaN() is a Double struct method. This method is used to check whether the specified value is not a number (NaN). Return Type: This function returns a Boolean value i.e. True, if specified value is not a number(NaN), otherwise returns False. Code: To demonstrate the Double.

Does any return null?

Returning null is often a violation of the fail fast programming principle. The null can appear due to some issue in the application. The issue can even go to production if the developer has not implemented proper exception handling, which can help quickly detect the issue.


1 Answers

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().

like image 121
CodesInChaos Avatar answered Oct 22 '22 05:10

CodesInChaos