Link to home
Start Free TrialLog in
Avatar of gromul
gromul

asked on

Switch differences between C++ and C#

I know that using break statement like in C++ works, but what is the intended way of writing a switch statement in C#? If I don't want any fall-through, do I need any break at all? Only at the end of switch statement?

Thanks
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Avatar of dstanley9
dstanley9

You can't have fall-through in C#.  C# forces you to break between cases, unless you're handling multiple cases with the same block:

switch (myValue)
{
  case 1:
   // do stuff
   break;
  case 2:
    // do stuff
    // compiler will error here as you must break from this case before moving to the next one
  case 3:
  case 4:
   // do stuff
   // this is legal since case 3 and case 4 are both handled here
   break;
}
Avatar of gromul

ASKER

I already found the first of these pages. So why do I need break in the default case?
>So why do I need break in the default case?
because C# rules it like that. to protect against weak programming...
its like dstanley9 , c# does not allow any fall-throughs, which would be one missing break in the default case.
Avatar of gromul

ASKER

My understanding is, C++ forces you to break between cases if you don't want fall through. C# doesn't have fall through, unless explicitate it with goto statements:

switch (i) {
   case 0:
      CaseZero();
      goto case 1;
   case 1:
      CaseZeroOrOne();
      goto default;
   default:
      CaseAny();
      break;
}
SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That is correct.  Like AngelIII said, it's to protect against unintended fall-through.
Avatar of gromul

ASKER

I see. Thanks
Avatar of gromul

ASKER

If I use the default case for errors and return, say, -1, then I don't need the break statement in the default case, right?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gromul

ASKER

Thanks