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

前端 未结 8 1284
孤城傲影
孤城傲影 2021-02-02 05:33

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.

相关标签:
8条回答
  • 2021-02-02 06:08

    The Any method runs against an IEnumerable and tells you whether there are any items in the Enumerable. If you don't give it anything to enumerate then an ArgumentNullException is reasonable: a collection with no (matching) elements is different to no collecion.

    0 讨论(0)
  • 2021-02-02 06:08

    As others have already mentioned, Any checks whether or not a sequence contains elements. It does not prevent you from passing null values(what might the bug in the first place).

    Every extension method in Enumerable class throws an an ArgumentNullException if the source is null. Throwing ArgumentNullExceptions in extensions actually is good practise.

    0 讨论(0)
提交回复
热议问题