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

前端 未结 8 1306
孤城傲影
孤城傲影 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:53

    Any() is an extension method that throws ArgumentNullException if the source is null. Would you perform an action on nothing? In general, it's better to get some explicit indicator of what's happening in the code rather than the default value.

    But it doesn't mean it can't be like that. If you know what you doing, write your own custom implementation.

    I just wanted to share with you some practical advice my company is following. We write our custom packages shared with private NuGet that are widely used in our products. Checking if the list is null/empty is very frequent, so we decided to write our implementation of Any which makes our code shorter and simpler.

提交回复
热议问题