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 1386
感动是毒
感动是毒 2020-12-20 12:09
string[] arrTopics = {\"Health\", \"Science\", \"Politics\"};

I have an if statement like:

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


        
相关标签:
9条回答
  • 2020-12-20 12:15

    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)
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
  • 2020-12-20 12:21

    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.

    0 讨论(0)
  • 2020-12-20 12:24

    Because Count method always returns integer if no elements in array it will return 0 other wise it will return number of elements. So what you need to do is just instead != null make it != 0 or > 0

    0 讨论(0)
  • 2020-12-20 12:24

    To figure it out, look into geclaration of Count() extension method.

    Puzzle of two pieces:

    1. You are trying to compare non-nullable type (value of type int) with null, so non-nullable types is never being referenced to, because all non-nullable types are value types in C#, which can not be referenced.

    2. Inequality defined through equality oerator in object class, which is defined in base. so your code mentioned above can be perfectly valid. Unfortunately, to distinguish situation when this appearance of equality operator in not desired (not overridden) in base classes there are some compiler warinings about it, because you will really get a always-false condition for incompatible types (or get an always-true condition in inequality operator)

    And value types (non-nullable) and nullable types (referenced types) are incompatible types in C#. For more info look into ECMA papers for standart of definition for type system being used in a C# language.

    0 讨论(0)
  • 2020-12-20 12:26

    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.

    0 讨论(0)
提交回复
热议问题