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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When dealing with reference types, a
nullvalue is semantically different from an “empty” value.A
nullstring is not the same asstring.Empty, and anullIEnumerable<T>is not the same asEnumerable.Empty<T>(or any other “empty” enumerable of that type).If
Anywere not an extension method, calling it onnullwould result inNullReferenceException. Since it is an extension method, throwing some exception (although not necessary) is a good idea because it preserves the well-known semantics of trying to call a method onnull: BOOM!