Trying to understand ?. (null-conditional) operator in C#
Solution 1:
-
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
.
Solution 2:
In your first case (list?.Count
) the operator returns an int?
- a nullable int
.
The >
operator is defined for nullable integers so that if the int?
has no value (is null), the comparison will return false
.
In your second example (a?.B
) a bool?
is returned (because if a
is null, neither true
nor false
but null
is returned). And bool?
cannot be used in an if
statement as the if
statement requires a (non-nullable) bool
.
You can change that statement to:
if (a?.B ?? false)
to make it work again. So the null-coalescing operator (??
) returns false
when the null-conditional operator (?.
) returned null
.
Or (as TheLethalCoder suggested):
if (a?.B == true)