Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

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?

like image 299
Maya Avatar asked Jul 20 '11 16:07

Maya


People also ask

What happens if you cast null to int?

In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.

Which statement is true about nullable type?

Characteristics of Nullable TypesNullable types can only be used with value types. The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value. The HasValue property returns true if the variable contains a value, or false if it is null. You can only use == and !=

Can an int have null in C#?

No, because int is a value type. int is a Value type like Date , double , etc. So there is no way to assigned a null value.


2 Answers

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.

like image 172
mdm Avatar answered Oct 20 '22 00:10

mdm


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) ...
like image 28
BonyT Avatar answered Oct 20 '22 01:10

BonyT