1

Possible Duplicate:
Switch statement fallthrough in C#?

The following code is illegal in C# because control cannot fall through from one case label to another. However, this behaviour is perfectly legal in C++. So, how would you go about coding the same behaviour in C#?

enum TotalWords
{
   One = 1,
   Two,
   Three,
   Four
}

public String SomeMethod(TotalWords totalWords)
{     
     String phrase = "";

     switch (totalWords)
     {
        case TotalWords.Four:
             phrase = "Fox" + phrase;
        case TotalWords.Three:
             phrase = "Brown" + phrase;
        case TotalWords.Two:
             phrase = "Quick" + phrase;
        case TotalWords.One:
             phrase = "The" + phrase;
             break;

        default:
             break;
     }

     return phrase;
}
Community
  • 1
  • 1
Lopper
  • 3,499
  • 7
  • 38
  • 57

2 Answers2

4

Eric Lippert, who works on the language, talks about it here:
http://ericlippert.com/2009/08/13/four-switch-oddities/

Short version: the easiest fix is to use a goto:

switch (totalWords)
 {
    case TotalWords.Four:
         phrase = "Fox" + phrase;
         goto case TotalWords.Three;
    case TotalWords.Three:
         phrase = "Brown" + phrase;
         goto case TotalWords.Two;
    case TotalWords.Two:
         phrase = "Quick" + phrase;
         goto case TotalWords.One;
    case TotalWords.One:
         phrase = "The" + phrase;
         break;

    default:
         break;
 }

I think the rationale here is that 9 times out of 10 a missing break is a bug rather than intentional. Forcing you to use break and an explicit branch helps keep you from writing bugs and makes it clear to future maintainters that the fall-through is intentional.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • "I think the rationale here is that 9 times out of 10 a missing break is a bug rather than intentional." - which is exactly why they should have never required it in the first place. – BlueRaja - Danny Pflughoeft Jan 07 '10 at 03:16
  • So you think switch shouldn't need the `break;` and just do it automatically at label boundaries? That's how VB does it. – Joel Coehoorn Jan 07 '10 at 03:41
0

Given that this is a numeric enumeration, and you're doing essentially the same operation in all cases, you can re-write it as a loop:

String[] phrase_bits = new String[] { "The", "Quick", "Brown", "Fox" };

public String SomeMethod(TotalWords totalWords)
{
    int x = (int) totalWords;
    String phrase = ""
    while (--x >= 0) {
        phrase = phrase_bits[x] + phrase
    }
    return phrase
}

This is not a generic answer for all switch statements, but for this case it's fairly nice.

Crast
  • 15,996
  • 5
  • 45
  • 53
  • It assumes that TotalWords is linear though, which it is in this case, but if it would be i.e. a flag (1,2,4,8), it would fail. – Michael Stum Jan 07 '10 at 02:53