Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"use of unassigned variable" compile error that will never happen

I have the following code, which results in a compile error, despite seemingly being correct:

bool aBool = SomePredicate();
if (!aBool && !OutFunction(out int value))
{
    return;
}
int result = -1; //other code here...
if (!aBool && SomeCondition(result, value)) // CS0165: Use of unassigned variable 'value'.
{

}

The variable aBool is not modified between the two conditions, meaning that if aBool was false during the first check it’ll always be assigned.
Otherwise, if aBool was true, then the variable would never be used, as the expression should end once the first part is evaluated.

Despite this, why does this result in a compile error? (C# 7.3)
Additionally, what is the best way to get around it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Main focus is on the "Why?" part

>Solution :

&& is a short-circuiting AND so if !aBool is evaluated to false, !OutFunction(out int value) is never evaluated and the method continues, so at SomeCondition(result, value) value can be not initiated.

You can try using Logical AND operator &:

bool aBool = SomePredicate();
if (!aBool & !OutFunction(out int value))
{
    return;
}
int result = -1; //other code here...
if (!aBool && SomeCondition(result, value))
{

}

bool SomePredicate() => false;
bool OutFunction(out int i) => false;
bool SomeCondition(int i, int j) => false;

So it always executes (Demo @sharplab.io). Or rewrite code in some other way (for example by declaring and initializing the variable before the OutFunction call).

Compiler has some limitations of conditional flow and definite assignment analysis when it comes to such checks and it seems that this is one of the corner cases. Some of them were recently fixed for later compilers with C# 10 feature Improved Definite Assignment Analysis.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading