C# compiler error: not all code paths return a value

C# compiler error: not all code paths return a value

Youre missing a return statement.

When the compiler looks at your code, its sees a third path (the else you didnt code for) that could occur but doesnt return a value. Hence not all code paths return a value.

For my suggested fix, I put a return after your loop ends. The other obvious spot – adding an else that had a return value to the if-else-if – would break the for loop.

public static bool isTwenty(int num)
{
    for(int j = 1; j <= 20; j++)
    {
        if(num % j != 0)
        {
            return false;
        }
        else if(num % j == 0 && num == 20)
        {
            return true;
        }
    }
    return false;  //This is your missing statement
}

The compiler doesnt get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.

Instead of returning in the last iteration, just return true after the loop:

public static bool isTwenty(int num) {
  for(int j = 1; j <= 20; j++) {
    if(num % j != 0) {
      return false;
    }
  }
  return true;
}

Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.

C# compiler error: not all code paths return a value

I also experienced this problem and found the easy solution to be

public string ReturnValues()
{
    string _var = ; // Setting an innitial value

    if (.....)  // Looking at conditions
    {
        _var = true; // Re-assign the value of _var
    }

    return _var; // Return the value of var
}

This also works with other return types and gives the least amount of problems

The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.

Leave a Reply

Your email address will not be published.