Why does the MS C# compiler complain that "not all code paths return a value" in the following scenario?
public int Foo(bool flag)
{
if(flag)
{
return 1;
}
else
{
ThrowException(); // this method always throws an exception
// return -1; // why do I need to add this code that will never be called?
}
}
Thanks!
It can't guess that ThrowException() is a method that always throws exceptions. For that you'd need static code analysis.
Static code analysis is available in VS 2010, but only for the more expensive versions of VS, I believe.
The else
branch does not have a return
statement. That means that Foo
does not return a value when entering the else
branch.
Why don't you do:
public int Foo(bool flag)
{
if (!flag) {
ThrowException();
}
return 1;
}
BTW I always feel that validation should be done first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With