Why is my variable still "uninitialized"?
c#
Solution
Some background from the C# specification (5.3.3.14):
For a try statement stmt of the form:
try try-block finally finally-block
(...)
The definite assignment state of v at the beginning of finally-block is the same as the definite assignment state of v at the beginning of stmt.
Edit Try-Catch-Finally(5.3.3.15):
Definite assignment analysis for a try-catch-finally statement (...) is done as if the statement were a try-finally statement enclosing a try-catch statement
The following example demonstrates how the different blocks of a try statement (§8.10) affect definite assignment.
class A
{
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
}
}
I just thought of an example that shows the problem better:
int i;
try
{
i = int.Parse("a");
}
catch
{
i = int.Parse("b");
}
finally
{
Console.Write(i);
}
Problem
``` string foo; try { foo = "test"; // yeah, i know ... } catch // yeah, i know this one too :) { foo = null; } finally { Console.WriteLine(foo); // argh ... @#! } Console.WriteLine(foo); // but nothing to complain about here ``` Besides it's not BP (catching-routing) - but this is the best isolation I can get. But I get nice waves telling me "danger, danger - might be uninitialized". How comes? Edit: Please do not suggest "Simply put a `string foo = string.Empty;` at the 'declaration'". I'd like to declare it, but just do the assignment on time!