|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
Flow Control (C# vs. Java)
Flow control statements, such as if else and switch statements, are very similar in both Java and C#.
Branching statements change the flow of program execution at run time according to certain conditions.
if, else, and else if
These statements are identical in both languages.
The switch Statement
In both languages, the switchstatement provides conditional multiple branching operations. There is a difference though in that Java enables you to "fall through" a case and execute the next case unless you use a break statement at the end of the case. C#, however, requires the use of either a break or a goto statement at the end of each case, and if neither is present, the compiler produces the following error:
Control cannot fall through from one case label to another.
Note that where a case does not specify any code to execute when that case is matched, control will fall through to the subsequent case. When using
goto in a switch statement, you can only jump to another case block in the same switch. If you want to jump to the default case, you would use
goto default. Otherwise, you would use
goto case cond, where
cond is the matching condition of the case you intend to jump to. Another difference from Java's switch is that in Java, you can only switch on integer types, while C# enables you to switch on a string variable.
For example, the following would be valid in C#, but not in Java:
The Return of goto
In Java, goto is a reserved keyword that is not implemented. However, you can use labeled statements with break or continueto achieve a similar purpose as goto.
C# does allow the goto statement to jump to a labeled statement. Note, though, that in order to jump to a particular label, the goto statement must be within the scope of the label. In other words, goto may not be used to jump into a statement block, although it can jump out of one, to jump out of a class, or to exit the finally block in try...catch statements. The use of goto is discouraged in most cases, as it contravenes good object-oriented programming practice.