tags:

views:

225

answers:

3
+2  Q: 

C# switch/break

It appears I need to use a break in each case block in my switch statement using C#.

I can see the reason for this in other languages where you can fall through to the next case statement.

Is it possible for case blocks to fall through to other case blocks?

Thanks very much, really appreciated!

+2  A: 

C# doesn't support implicit fall through construct, but the break (or goto) nonetheless has to be there (msdn). The only thing you can do is stack cases in the following manner:

switch(something) {
    case 1:
    case 2:
      //do something
      break;
    case 3:
      //do something else
}

but that break (or another jump statement like goto) just needs to be there.

Marek Karbarz
This is not quite accurate. It's not that a "jump" statement (by which I assume you mean break, continue, goto, return or throw) has to be at the end, it's that a statement with an unreachable end point has to be at the end. All the "jump" statements have that property, but there are also other statements with that property. For example, it's perfectly legal, though rare, to end a switch section with "while(true) M();"
Eric Lippert
I see that the MSDN documentation is incorrect. I'll have a talk with the documentation manager.
Eric Lippert
+11  A: 

Yes, you can fall through to the next case block in two ways. You can use empty cases, which doesn't need a break, and you can use goto to jump to the next (or any) case:

switch (n) {
  case 1:
  case 2:
  case 3:
    Console.WriteLine("1, 2 or 3");
    goto case 4;
  case 4:
    Console.WriteLine(4);
    break;
}
Guffa
+2  A: 

The enforcement of "break" is there to stop bugs. If you need to force a fall-thru then use "goto case " (replace the with appropriate value)

the following example shows what you can do:

switch(n)
{
    case 1:
    case 2:
      //do something for 1+2
      //...
      goto case 3;
    case 3:
      //do something for 3, and also extra for 1+2
      //...
      break;
    default:
      //do something for all other values
      //...
      break;
}

See http://msdn.microsoft.com/en-us/library/06tc147t%28VS.80%29.aspx

Will