I have two methods, both compile correctly:
public int A() { int i; if(!int.TryParse("0", out i)) { return -1; } // do sth return i; } public int B() { int i; if(true) { return -1; } return i; }
In the second case (method B ), the compiler is smart enough to detect that the variable i never used, so it does not complain that it does not assign it.
However, I have another example (a combination of both) that seems to be equivalent to method B :
public int C() { int i; if (true || !int.TryParse("0", out i)) { return -1; } return i; }
When compiling on Windows under VisualStudio 2012 (.NET Framework 4.6.01055), it gives an error: Use of unassigned local variable 'i' . Decision:
- initialize
i any value or - use
| instead of || .
Why is this so? It seems that the compiler has all the necessary data to detect unreachable code.
Side note . Example C compiles on Linux in mono version 4.6.2 with warnings about unreachable code, as expected.
houen source share