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
Thanks
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;
}
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;
}
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...
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.
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;
}
switch (i) {
case 0:
CaseZero();
goto case 1;
case 1:
CaseZeroOrOne();
goto default;
default:
CaseAny();
break;
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
That is correct. Like AngelIII said, it's to protect against unintended fall-through.
ASKER
I see. Thanks
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks
http://www.jaggersoft.com/csharp_standard/15.7.2.htm