string[] arrTopics = {\"Health\", \"Science\", \"Politics\"};
I have an if statement like:
if (arrTopics.Count() != null)
<
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)
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.
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.
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
To figure it out, look into geclaration of Count() extension method.
Puzzle of two pieces:
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.
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.
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.