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

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

    When dealing with reference types, a null value is semantically different from an "empty" value.

    A null string is not the same as string.Empty, and a null IEnumerable is not the same as Enumerable.Empty (or any other "empty" enumerable of that type).

    If Any were not an extension method, calling it on null would result in NullReferenceException. 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 on null: BOOM!

提交回复
热议问题