Why am I getting “CS0472: The result of the expression is always true since a value of type int is never equal to null of type int?”

后端 未结 9 1421
感动是毒
感动是毒 2020-12-20 12:09
string[] arrTopics = {\"Health\", \"Science\", \"Politics\"};

I have an if statement like:

 if (arrTopics.Count() != null)
<         


        
9条回答
  •  Happy的楠姐
    2020-12-20 12:15

    Your if statement doesn't look right. I assume. You either meant to

    if(arrTopics?.Count() != null)
    

    OR

    if (arrTopics.Any())
    

    OR

    if (arrTopics != null)
    

    Explanation: sequence.Count() returns int which is never null. Adding the question mark ? returns Nullable instead of int. Also Count() expects the sequence to be instantiated. using Count() method on a null sequence results in ArgumentNullException; so you always need to check against null reference, before going for Count(), Any() extension methods, or use the question mark.

提交回复
热议问题