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

user115185 picture user115185 · Jan 17, 2014 · Viewed 331.5k times · Source

I'm trying to write code that returns whether or not a given integer is divisible evenly by 1 to 20,
but I keep receiving the following error:

error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value

Here is my code:

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;
        }
    }
}

Answer

user1345223 picture user1345223 · Jan 17, 2014

You're missing a return statement.

When the compiler looks at your code, it's sees a third path (the else you didn't code for) that could occur but doesn't 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
}