. Advertisement .
..3..
. Advertisement .
..4..
I am tired of fixing the problem: c# not all code paths return a value in the csharp; even if I get the reference from another forum, it still returns an error:
error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value
To identify the problem, I will show you the detail here:
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;
}
}
}
How do I do that? Could you support me in improving this problem?
The cause: The reason for the problem “c# not all code paths return a value” is that your loop’s return position does not match. The compiler doesn’t understand the complicated logic of returning in the last iteration of the loop, so it believes you might quit the loop and return nothing.
Solution: To solve the error, you should return true after the loop instead of returning on the last iteration. Do simply like this code, so the compiler can easily receive your demand:
The compiler does not understand the complex logic of returning in the last loop iteration. It thinks you could exit the loop without ever returning anything.
Do not return in the previous iteration. Instead, return true after the loop.
Side note: There is a logic error in the original code. While you are checking
num == 20
in this last condition, it is important to checkj == 20
. You should also check ifnum % j == 0
is superflous. This is because it is always true once you reach there.