I have the following code:
if (Model.Products?.Cards?.Any())
{
}
If I try this it throws an error:
Cannot convert bool? to bool
Having searched for this this I'm not sure why the error is thrown, where as it will allow me to do
if (Model.Products?.Cards?.Count > 0)
{
}
Why am I unable to use .Any()
in this case - why is it classed as a nullable bool yet the count isn't a nullable int?
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.
(a ?: b) is equivalent to (if (a != null) a else b). So checking a nullable Boolean to true can be shortly done with the elvis operator like that: if ( a ?: false ) { ... } else { .... }
False is a value, null is lack of a value. C# gets it right I think. Other languages that were built without a boolean type or a concept of a pointer (or nullable type) just overloaded an int to mean all these different things.
C# has two different categories of types: value types and reference types. Amongst other, more important distinctions, value types, such as bool or int, cannot contain null values.
Simply because it is valid do a greater than on a Nullable<int>
and int
:
if (null > 0)
{
}
null
is considered a Nullable<int>
here, and comparing Nullable<int>
with int
is okay. (Required reading: How does comparison operator works with null int?)
But not a if (null)
. An if
statement required a boolean.
The required workaround could be:
if (Model.Products?.Cards?.Any() ?? false)
{ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With