Why in code like below is the .NET compiler not able to establish that all code paths do return a value?
bool Test(bool param) {
bool test = true;
if (param)
test = false;
else
test = false;
if (!test)
return false;
}
error CS0161: Not all code paths return a value!
The code can be refactored – but the compiler is not suggesting that. Yet all return paths are covered – so why does the compiler complain that they are not?
Edit: I guess the conclusion here is that:
(error CS0161) + (all code paths obviously return a value) => refactor code.
Once you get the habit of that translation I guess everything is ok.
From the C# Language Specification 4.0 included with Visual Studio 2010.
The definition of reachability is here (emphasis added):
Since
!testisn’t a constant expression (even though it will always evaluate totrue), the compiler is obliged to not consider it in the flow analysis. One reason (maybe the only reason) for this restriction is that performing this kind of flow analysis is impossible in the general case.To get rid of the error, you’ll need to have another
returnstatement, either in anelseclause or unconditionally at the end of the method.