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?"

Viewed 29434
string[] arrTopics = {"Health", "Science", "Politics"};

I have an if statement like:

 if (arrTopics.Count() != null)

When I hover my mouse over the above statement, it says:

Warning CS0472: The result of the expression is always true since a value of type int is never equal to null of type int?

I am not able to figure out why it is saying so. Can anybody help me?

9 Answers

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<int> 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.

Related