Wednesday, April 7, 2010

Switch statements

In VB there was Select Case. In C# there is the switch statement.

The following is best practice on how you should handle cases that do
the same logic when hit.
using fall through on the case:

int x = 1;
switch ( x )
{
case 1:
case 2:
/* code here */
break;
case 3:
/* code here */
break;
default:
break;
}

The following while doable should not be used because it promotes
unreadable code, adding to complexity and potential for bugs:
Or use goto case statements:

int x = 1;
switch ( x )
{
case 1:
goto case 2;
case 2:
goto case 5;
break;
case 3:
/* code here */
break;
case 4:
goto case 2;
break;
case 5:
/* code here */
break;
case 6:
/* code here */
break;
case 7:
goto case 5;
break;
case 8:
/* code here */
break;
case 9:
goto case 2;
break;
default:
break;
}

No comments: