I have this very simple example:
class Program
{
class A
{
public bool B;
}
static void Main()
{
System.Collections.ArrayList list = null;
if (list?.Count > 0)
{
System.Console.WriteLine("Contains elements");
}
A a = null;
if (a?.B)
{
System.Console.WriteLine("Is initialized");
}
}
}
The line if (list?.Count > 0)
compiles perfectly which means that if list
is null
, the expression Count > 0
becomes false
by default.
However, the line if (a?.B)
throws a compiler error saying I can't implicitly convert bool?
to bool
.
Why is one different from the other?
list?.Count > 0
: Here you compare an int?
to an int
, yielding a bool
, since lifted comparison operators return a bool
, not a bool?
.a?.B
: Here, you have a bool?
. if
, however, requires a bool
.