switch statement weirdness

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am new to C# and couldn't figure out the rationale for the error "Control cannot fall through from one case label ('case 2:') to another" in the switch statement in this example

int n = 1
switch (n

case 0
Console.WriteLine("0")
break
case 1
Console.WriteLine("1")
break
case 2
Console.WriteLine("2")


Adding a "break;" for case 2 fixes the problem but I'd have expected the compiler to not expect it since there is no other clause to process after this one. I can understand the error being flagged for case 0, 1 but not for 2
 
Sri said:
[final case statement requires a break]
I'd have expected the compiler to not expect it
since there is no other clause to process after
this one.

Even the default case requires a break (unless it ends with a return or
throw statement).

Since C# doesn't allow 'fall-through' (allowing multiple case clauses to be
processed in order), the break seems unnecessary anyway. It does help you to
avoid subtle bugs when porting code from C++, but I'm not convinced that
that really justifies it.

P.
 
Paul said:
Even the default case requires a break (unless it ends with a return or
throw statement).

Or a goto... I use this to accomplish what "fall-through" did in C/C++.
If I have three cases that ultimately run much of the same code, they
can all do their preliminary stuff and then goto the proper _common_
case to finish up.
 
Back
Top