A colleague of mine just encountered an interesting problem. I recreated the issue with a simple example code below. The problem is that the compiler complains about i
possibly not being assigned when it is used in the third line.
I know that GetProperty
will not be executed, if o
is null
, and i
will then not be initialized, but in that case I would also not evalueate int i2 = i;
. Is there something about optionals or the null coalescing opertator I don't know that is relevant here, or is this simply a case where the compiler isn't intelligent enough to know that i
is not used if it is not initialized?
void Test(object o) {
if (o?.GetProperty("Blah", out int i) ?? false) {
int i2 = i;
}
}