Question

Note: I realize that this is poor code; the variable valid should just be deleted and the while loop should use while(true) and let the return value break out of it. But, since I am trying to learn how compilers work, I thought this would be applicable.

I have a very interesting predicament here. The code below displays a list of options to the user and returns the option they chose. This fails with "Not all code paths return a value (CS0161)".

public static int Menu(params string[] list) {
    string input;
    bool valid = false;
    while (!valid) {
        for(int i = 0; i < list.Length; i++) {
            Console.WriteLine(i + ": " + list[i]);
        }
        input = Console.ReadLine();
        for (int i = 0; i < list.Length; i++) {
            if (input == i.ToString()) {
                valid = true;
                return i;
            }
        }
    }
    //return -1;
}

However, if I uncomment the return -1 line, the code will function appropriately while at the same time producing dead code; the while loop can only ever exit at the same time that a value is returned, and it is always returned. (No warning is generated saying that this is unreachable code.)

Why does the code fail, saying that it doesn't always return a value when in fact it does?

Was it helpful?

Solution

The compiler does not check for values of variables. It only sees your while-loop with a boolean variable

int Method {
    while([a variable]) {
        <Optional path>
    }
    <Path that is checked>
}

and notes that if it would be false your method does not return an int as it was said it would.

See this answer for a more detailed explanation based on the C# language specification.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top