Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ?.Any() classed as a nullable bool?

Tags:

c#

linq

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?

like image 425
Pete Avatar asked Apr 17 '18 14:04

Pete


People also ask

What is a nullable bool?

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.

How do you check if a Boolean is nullable?

(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 { .... }

IS null Boolean false C#?

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.

Can you set a bool to null?

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.


1 Answers

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)
{ }
like image 163
Patrick Hofman Avatar answered Sep 18 '22 04:09

Patrick Hofman