Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what a case won't this function return a value? Why does the compiler report an error?

public static int Test(int n)
{
  if (n < 0) return 1;
  if (n == 0) return 2;
  if (n > 0) return 3;
}

Compiler (Visual Studio 2010, C# 4.0) says "Not all code paths return a value". Why?

like image 602
Ivan Avatar asked Jun 29 '11 21:06

Ivan


4 Answers

The compiler doesn't try to determine that this covers all the possible values of n. All it sees is that you have three if statements, and it assumes that it's possible for all of them to be false... in which case you'd reach the end of the method without returning a value.

See this blog post from Eric Lippert for more details about the compiler's limits when it comes to reachability.

Just make the final return unconditional.

like image 86
Jon Skeet Avatar answered Oct 24 '22 03:10

Jon Skeet


The compiler isn't looking at your conditions. Even though you are correct that at least one of your if-blocks will run, you still need to refactor to something like this:

if (n < 0)
    return 1;
else if (n == 0)
    return 2;
else
    return 3;
like image 42
FishBasketGordo Avatar answered Oct 24 '22 02:10

FishBasketGordo


The compiler isn't smart enough to know that all of those branches are mutually exclusive, so it worries about the fallthrough case where all three if statements fail.

You can either link all the if statements with else and use only else for the last condition, or you can return a default value at the end. This will get around the issue.

like image 2
Platinum Azure Avatar answered Oct 24 '22 03:10

Platinum Azure


The compiler doesn't know you've covered all your bases. You can rewrite it like this...

public static int Test(int n)
{
  if (n < 0) return 1;
  else if (n == 0) return 2;
  else (n > 0) return 3;
}

or this...

public static int Test(int n)
{
  if (n < 0) return 1;
  if (n == 0) return 2;
  if (n > 0) return 3;
  return 4; //will never occur
}
like image 1
Narnian Avatar answered Oct 24 '22 02:10

Narnian