C# FAQ: Why does not the CSharp switch statement work like I expect it to?
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:FAQs |
| edit |
[edit]
Why doesn't the C# switch statement work like I expect it to?
C# does not support automatic fall through for case blocks. With fall through, control automatically goes to the next case block even without writing any statement in the current case. But, one can use a goto statement to direct control to the next case block.
C# does not support the following code; so, it will not compile:
switch (caseVar) { case 0: // do something case 1: // do something additional to case 0 default: // do something additional to cases 0, 1 break; }
To accomplish what is intended in the previous example, modify the C# source code to use explicit flow control as follows:
class SwitchTest { public static void Main() { int var = 3; switch (caseVar) { case 0: // do something goto case 1; case 1: // do something additional to case 0 goto default; default: // do something additional to cases 0, 1 break; } } }