I have two methods, both of them compiles 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
) compiler is smart enough to detect that variable i
is never used so it doesn't complain about not assigning 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 throws an error: Use of unassigned local variable 'i'
. The solution is to:
- initialize
i
with any value, or - use
|
operator instead of||
.
Why is that so? It looks like a compiler has all the necessary data to detect unreachable code.
Side note: Example C
compiles on Linux under mono 4.6.2 with warnings about unreachable code as expected.