Compiler Error CS0163
Updated: March 2012
When a case statement contains one or more statements and is followed by another case statement, you must explicitly terminate the case by using one of the following keywords:
return
goto
break
throw
continue
If you want to implement "fall through" behavior, use goto case #. For more information, see switch (C# Reference)
The following sample generates CS0163:
// CS0163.cs
public class MyClass
{
public static void Main()
{
int i = 0;
switch (i) // CS0163
{
case 1:
i++;
// uncomment one of the following lines to resolve
// return;
// break;
// goto case 3;
case 2:
i++;
return;
case 3:
i = 0;
return;
}
}
}
To the Change History: The continue keyword can be used to exit the case block if the whole switch statement is inside a loop (that is, inside a for, foreach, while, or do body).$0 $0 By the way, another legal way to avoid fall-through, is like this:$0 $0 case 1:$0 while (true)$0 Console.WriteLine("Will this ever stop?");$0 //this point is unreachable$0 $0 /JeppeSN$0 $0 $0
Edit by SJ at MSFT: If you use the continue keyword, you exit from the loop iteration, not from the case or the switch statement. In this example:
int caseSwitch = 1;
for (int i = 0; i < 5; i++)
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1...");
continue;
case 2:
Console.WriteLine("Case 2...");
break;
}
caseSwitch += 1;
Console.WriteLine("Out of switch but in loop");
}
The output is:
Case 1...
Case 1...
Case 1...
Case 1...
Case 1...
Variable caseSwitch is not incremented, and the last WriteLine is not executed.
Also, "while (true)" is valid but not very practical for most applications -- unless you have a lot of time on your hands.
Edit by Ben Voigt [Visual C++ MVP]: I fail to see why `continue` was removed from the list. Your reasoning is that it doesn't work like `break` and run the code following the switch? None of `return` or `throw` or `goto` continue execution following the switch either.
Edit by SJ at MSFT: Hmmmm, my example does resolve what would otherwise be a CS0163 error, which is the point here. I will look back through the history of the topic to see what occasioned the change. Perhaps I can rephrase.
- 9/20/2011
- JeppeSN1
- 1/4/2012
- SJ at MSFT