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;
}
}
you are using Null Conditional Access with o?
which means that there is a possibility that (whenever o is null) GetProperty
will not be called.
This introduces posibility of uninitialized i
. because out int i
won't be called in the case that o
is null.
the code can be tested by removing null conditional access
void Test(SomeClass o) {
if (o.GetProperty("Blah", out int i) ?? false) {
int i2 = i; //no-compiler error
}
}
on the above method, GetProperty method is always called and thus i
is always initialized and assigned.
On the other hand your code does not compile, object o
does not have .GetProperty
method on its own
if (o?.GetProperty("Blah", out int i) ?? false)
can be expanded as
if (o != null)
{
if (o.GetProperty("Blah", out int i))
{
}
}
else
{
//i is not defined in this context //
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With