Why is this code unreachable

I have the following code that is unreachable and i do not understand why:

Language CheckLanguage (int theLanguage) {

    switch (theLanguage) {
        case 0:
            return Language.English;
            break; << warning CS0162: Unreachable code detected
        case 1:
            return Language.Spanish;
            break;
   }
    return Language.Spanish;
}

Also, as i need a return in the bottom, tried without, and “null” does not work i have constructed it this way and it works. However, i guess this is part of the problem but what would be a better way of designing this piece of code?

It’s unreachable because when it hits the return, it returns. And when it returns, it doesn’t keep going to the break statement.

I’d do (for what you have there):

switch (theLanguage)
{
    case 0:
        return Language.English;
    default:
        return Language.Spanish;
}

The break is unreachable as the function will return before it gets to the break. However you can’t build a switch without the break statement. (I think)

That’s why its a warning, not an error. This code will still function.

But if it bothers you try this:

Language CheckLanguage (int theLanguage) {
    Language returnValue = Language.Spanish
    switch (theLanguage) {
        case 0:
            returnValue = Language.English;
            break; 
        case 1:
            returnValue = Language.Spanish;
            break;
   }
   return returnValue;
}

You can build a switch without the break as long as there’s a return statement, because it still prevents control falling through cases.

Edit: I believe it also works if you use a goto statement, but I’ve never actually used one.

1 Like

That’s useful to know. Thanks.

Really great and a BIG thank you it worked perfectly! Seeing the solution i should have figured that out myself but being a NooB in C# and Unity… :slight_smile: