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?
Best Answer
list?.Count > 0
: Here you compare anint?
to anint
, yielding abool
, since lifted comparison operators return abool
, not abool?
.a?.B
: Here, you have abool?
.if
, however, requires abool
.