|
Delphi |
|
If you have many nested if conditions, you can you case statement instead:
if C='A' then // 'A' char code
else
if C='B' then // 'B' char code
else
if C='C' then // 'C' char code
else
...
case C of
'A': // 'A' char code
'B': // 'B' char code
'C': // 'C' char code
...
end;
case can have else at the end:
case C of
'A': // 'A' char code
'B': // 'B' char code
'C': // 'C' char code
else // other chars code
end;
You can use begin end for multiline code, multiline code in the else can be placed without begin end:
case C of
'A':
begin
// multiline
// 'A' char code
end;
'B': // 'B' char code
'C': // 'C' char code
else
// multiline
// other chars code
end;
You can use several case values and values ranges:
case X of
1..9: SomeProcedure;
10,20,30,40: AnotherProcedure;
end;
case with else allows to change awkward if statements to short and readable code:
if (C='A') and (C='B') and (C='C') and (C='D') and (C='E') then SomeProcedure
else AnotherProcedure;
case C of
'A'..'E': SomeProcedure;
else AnotherProcedure;
end;
if (C<>'A') and (C<>'B') and (C<>'D') and (C<>'E') then SomeProcedure;
case C of
'A','B','D','E':; // do nothing
else SomeProcedure;
end;
|
|
C# |
|
switch is used like Delphi's case:
switch(C)
{
case 'A':
// 'A' char code
break;
case 'B':
// 'B' char code
break;
case 'C':
// 'C' char code
break;
default:
break;
}
As you can see, the break operator must be used to prevent executing the next case.
Like in Delphi, you can use several case values for one code:
switch(X)
{
case 'A':
case 'B':
// 'A' & 'B' char code
break;
case 'C':
// 'C' char code
break;
}
You can fall through from one case label to another with goto operator to optimize code (you can use one code fragment for several cases):
switch(X)
{
case 'A':
// 'A' char code
break;
case 'B':
// 'B' char code
goto case 'A'; // fall through case 'A'
case 'C':
// 'C' char code
break;
}
but avoid cyclic:
switch(X)
{
case 'A':
// 'A' char code
goto case 'B'; // fall through case 'B' // cyclic!!!
case 'B':
// 'B' char code
goto case 'A'; // fall through case 'A'
}
|
|
Ranges cannot be used in case. |
|
|
|
goto operator allows to use one code for different cases. |
|
|
|
Do not forget about break and be careful with goto. |
|
|
|
|
|
|
|
|
|
|
|