Home > Software design >  Variable out of scope error with (I assume) the correct scope declaration - C#
Variable out of scope error with (I assume) the correct scope declaration - C#

Time:06-30

The use-case is a GUI with a checkbox, where I only want to run the compliance check (an external python script) if the checkbox is marked. If the compliance check runs, I want to save the output string from the processing.

Here is a snapshot of my code:

Task<string> comp_python;
if (compliance) // compliance is t/f based on whether the checkbox is marked
{
    string cmd = "some python command";
    comp_python = runCompAsync(cmd);
}

// some processing

if (compliance)
{
    string comp_res = await comp_python; // out of scope error here on comp_python
}

I am getting an out of scope error on the comp_python Task object in the second conditional. I have tried removing all of the processing between these two blocks and my scope is still wrong. Any ideas?

If this can be accomplished another way with reworked code, I can accept an alternative solution as well.

CodePudding user response:

The rules of reachability and definite assignment do not know that compliance is the same value at both if statements. Thus, the compiler considers it possible that it is false at the first if, and true at the second if. comp_python will never have been assigned on that path; it was declared but it was never definitely assigned per the definite assignment rules. (A local variable is not null / default if it's left unassigned, it is a compiler error if a possibly-unassigned local is accessed.)

One way to fix this is to split out your intervening code into another method (or a local method if this is the only method that uses it), allowing you to have the declaration, assignment, and usage of the local all be in one block.

if (compliance) // compliance is t/f based on whether the checkbox is marked
{
    string cmd = "some python command";
    Task<string> comp_python = runCompAsync(cmd);

    someProcessing();

    string comp_res = await comp_python;
}
else
{
    someProcessing();
}

Language specification reference: reachability and definite assignment.

  • Related