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?
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)
{ }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.