Visual Studio marks the code just after & ldquo; case variable: & rdquo; inaccessible

advertisements

I have a switch statement with multiple cases:

ConversionState state = ConversionState.Start; // enum
for(int i = 0; i < source.Length; i ++)
{
    switch(state)
    {
        case ConversionState.Start:
            state = ConversionState.Name; // <-- warning here
            name += source[i]; // source is a string
            break;
        case ConversionState.Name:
            if(source[i] == ' ') // <-- warning here
            {
                name = name.ToLower();
                if(name[0] == '/')
                    name = name.SubString(1);
                state = ConversionState.Between;
            }
            else
                name += source[i];
            break;
        case ConversionState.Between: // no code in this case statement, yet to be implemented
            break; // <-- warning here
    }
}

I get a warning on the three marked lines: "unreachable code detected". The very first statement after a case can't be unreachable, can it? My questions are:

  1. Is something wrong with my code, or is the warning wrong?

  2. If VS2015 thinks a code snippet is unreachable, does it get removed when I compile with optimizations on? If not, should I just ignore this warning?

  3. Does this warning mean that the marked line is unreachable, or that the whole case is unreachable?

PS: I know that the current code can be rewritten without switch, and that would solve the problem, but the future code that will be added will make it - MUCH - easier to maintain using a switch.

Edit (requested by amit dayama):

private enum ConversionState
{
  Start, Between, Name, Argument, Switch
}

The enum is inside the class that has the method that contains the originally posted code.

Edit 2: The very first line of the method this code is in was throw new NotImplementedException();. Apparently, this makes Visual Studio mark the first line of every case in every switch in the method unreachable, but nothing else, and, interestingly, not the entire code following the exception.


I have checked your code and everything compiles and builds on my side, using VS2012. I now there are a few problems with VS2015, with a lot of false positives in Error List Window.

So question 1: from my side, your code is correct.

Question 2: Not entirely sure, but believe that id does not remove it for optimization. I can be wrong, but the reason for the warning is that you address it and not the compiler. I will add comment when I found the correct answer for you.

Question 3: the line not the entire case.

PS: maybe you can try and add the curly braces into some of your if and else statements. I know they are not required for one liners, but they might be causing the specific behavior in VS2015