Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional null coalescence in if clause [duplicate]

Tags:

c#

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;
    }
}
like image 681
Piflik Avatar asked Feb 13 '19 09:02

Piflik


1 Answers

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 //
}
like image 178
Derviş Kayımbaşıoğlu Avatar answered Sep 29 '22 03:09

Derviş Kayımbaşıoğlu