When using the Switch statement, is using return instead of break or a combinati
ID: 645897 • Letter: W
Question
When using the Switch statement, is using return instead of break or a combination of the two considered bad form?
while (true)
{
var operation = Randomness.Next(0, 3);
switch (operation)
{
case 0:
return result + number;
case 1:
if ((result - number) > 0)
{
return result - number;
}
break;
case 2:
return result * number;
case 3:
if ((result % number) == 0)
{
return result / number;
}
break;
}
}
Explanation / Answer
The break statement is required in case 1 and case 3. If you omit it, the code will not compile, because the if body is not guaranteed to execute, and fall-through in switch statements is not allowed in C#.
The break statement is not required in case 0 and case 2, because the return always executes; code execution will never reach the break statement. The compiler will issue a warning if you include the break statement, but the code will compile.
Not having break statements can be useful in simplifying certain mapping or factory functions:
public string NumericString(int digit)
{
switch (digit)
{
case 1: return "one";
case 2: return "two";
case 3: return "three";
// ..etc.
}
}
If you need fall-through behavior, you can simulate it with a goto, one of the few places in the C# language where using a goto actually makes sense, though it's arguable whether or not that constitutes good style.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.