In C #, why is the variable definitely not assigned at the beginning of the finally block?

I do not understand why the following code is causing an error. Usually I can understand things from the language specification, but in this case I don't understand the language specification.

This does not cause problems in my code, by the way, I just want to understand the language.

Example:

bool success;
try
{
    success = true;
}
catch
{
    success = false;
}
finally
{
    Console.WriteLine(success); // ERROR: Local variable 'success' might not be initialized before accessing
}

This behavior is similar to all versions of C #, but below are quotes from C # Language Specification 5.0 .

Section 5.3.3.14 Try-finally statements

The specific assignment state v at the beginning of the finally block is the same as the specific assignment state v at the beginning of stmt.

Here, "the beginning of stmt" refers to the beginning of the whole try-finally statement, i.e. immediately before try.

Section 5.3.3.15 Try-catch-finally statements

, try (§8.10) .

static void F() {
    int i, j;
    try {
        goto LABEL;
        // neither i nor j definitely assigned
        i = 1;
        // i definitely assigned
    }
    catch {
        // neither i nor j definitely assigned
        i = 3;
        // i definitely assigned
    }
    finally {
        // neither i nor j definitely assigned
        j = 5;
        // j definitely assigned
    }
    // i and j definitely assigned
  LABEL:;
    // j definitely assigned
}

- , success ( ) i ( ) finally-?

+4
2

- , try catch - , finally.

ThreadAbort try, .

, , catch (, .Net " " ).

, try catch finally.

+5
  • , catch, , catch. , .

  • ? , , , , . , , .

, .

+2

All Articles