I was wondering why C# requires me to use break in a switch statement although a fall-through semantics is by definition not allowed. hence, the compiler could generate the break at the end of each case-block and save me the hassle.
However, there is one scenario (which has already been discussed on this site) which I could come up with that might be the reason for the explicit usage of break:
switch (foo) {
case 0:
case 1:
bar();
break;
default:
break;
}
Here, the method bar() is called if foo has either the value 0 or 1.
This option would break in the truest sense of the word if the compiler would generate break statements by itself. Is this it, is this the reason why the break is compulsory or are there any other good reasons?
I suspect that the reason C# requires the developer to place a break or terminal statement at the end of each case is for clarity.
It avoids newcomers to the language from assuming that switch( ) in C# behaves like switch in C or C++ where fall through behavior occurs.
Only in the cases of adjacent empty cases does fall through occur in C# – which is relatively obvious.EDIT: Actually, in C# fallthrough is always illegal. What is legal, however, is having a single case associated with two or more labels. Eric Lippert writes at length about this behavior and how it differs from C/C++ switch statements.
You may be interested in reading this article on Eric Lipperts blog.