C# Safe navigation operator - what is actually going on?
Let's walk through this logically.
var f = ???;
var i = f?.Measure;
var t = i.HasValue;
We don't know if f
is null or not.
- If
f
is null, then the result (i
) isnull
- If
f
is not null, then the result (i
) is anint
Therefore, i
is defined as int?
, and t
is a bool
Now, let's walk through this:
var f = ???;
var i = f?.Measure.HasValue;
- If
f
is null, then the result (i
) is null - If
f
is not null, then the result (i
) isMeasure.HasValue
, which is a bool.
Therefore, i
is a bool?
.
If f
is null, we short-circuit and return null. If it's not, we return the bool
result of .HasValue
.
Essentially, when using ?.
- the return type must be a reference value, or a Nullable<T>
, as the expression can short circuit to return null.