问题
int x;
if (Q())
x = 123;
if (R())
Console.WriteLine(x); // illegal
int x;
if (Q())
x = 123;
if (false)
Console.WriteLine(x); // legal!!
May I know why second one is legal while former one is throwing 'using unassigned local variable' compile time exception?
回答1:
This tells compiler that the condition under if in the statement given below will never execute, so the constraint of unused variable does not apply to it.
if (false)
Console.WriteLine(x); // legal!!
回答2:
Because the second one is eliminated by compiler as never executed.
回答3:
If Q() == FALSE and R() == true, x is not set and it will try to use it.
来源:https://stackoverflow.com/questions/11071682/unassigned-local-variable-mystery