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?"
Solution 1
int
can never be equal to null. int?
is the nullable version, which can be equal to null.
You should check if(arrTopics.Count() != 0)
instead.
Solution 2
What are you trying to ask here?
Array.Count() returns an int which will never be null.
If you want to know if the Array has been initialised then:
if(arrTopics !=null) ...
if you want to know if it's been initialised but has no members then:
if(arrTopics.Count() > 0) ...
Solution 3
It means what it says.
The "Count" method returns a value type. It's an integer. It will always have a value where it's default value is zero.
Your check really should be:
if (arrTopics.Count() != 0)
Solution 4
null
represents the absence of any value, not the number 0
. And as the message says an int can never be null
since it's neither a reference type nor a nullable value type and thus always has some value.
Solution 5
Like the error says, int
can never be null. I'd change the code to
if (arrTopics != null && arrTopics.Any())
Or even more efficient if you know arrTopics is an array and never null is
arrTopics.Length != 0
Related videos on Youtube
Maya
Updated on July 18, 2022Comments
-
Maya almost 2 years
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?
-
Matt over 6 yearsPossible duplicate of Why type "int" is never equal to 'null'?
-
-
m.edmondson almost 13 yearsCouldn't have answered better myself. Just to add to this, and int cannot possibly be null as it is a value type not a reference type
-
Jon Skeet almost 13 years@m.edmondson: But
Nullable<int>
is a value type and that can have a null value, so your reasoning doesn't work. -
m.edmondson almost 13 years@Jon Skeet - Apologies if thats wrong, I was going off what I read in the docs that "Nullable types are instances of the System.Nullable struct."
-
Artur Mustafin almost 13 yearsCount() for an array is not a property - it is method
-
Jon Skeet almost 13 years@m.edmondson: Yes, the Nullable struct. So a reference type. More accurate would be: int cannot possible be null as it is a non-nullable value type, not a reference type or nullable value type.
-
Khepri almost 13 yearsWoops, yeah, mistype...my bad. Code said method, comment said property. I've straightened out the mis-alignment.
-
Alex Bagnolini almost 13 years@Jon: I guess you wanted to write "Yes, the Nullable struct. So a value type"