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

前端 未结 8 1305
孤城傲影
孤城傲影 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 05:51

    Any() is an extension method, so this is actually passed as the first argument to the method. In this situation, it's understandable for it to throw ArgumentNullException is this is null.

    You can perform the check yourself beforehand:

    bool hasAny = yourData == null ? false : yourData.Any(yourPredicate);
    

提交回复
热议问题