This is not specifically a C# question but it is the C# version of switch
that makes me ask the question.
Why do I have to explicitly state that I do not want to fall through from one case
statement to the next instead of instead indicating when I DO want to fall through?
In C#, the compiler will not let you fall through from one case
statement to the next (unless the case
statement is empty) and yet it forces you to put an explicit break
at the end of every one. The vast majority of switch
statements that I write have no fall through.
int x = 4;
string result;
switch (x)
{
case 1:
result = "One";
break;
case 2:
result = "A couple";
break;
case 3:
case 4:
result = "Three or four";
break;
/*
case 5:
result = "Five"; // Here be an error! A common typo for me!!!
*/
default:
result = "Five or more";
break;
}
The above example is contrived to show the possibilities. The number of times I actually fall-through (like between 3 and 4 above) is minimal. If I remove the comments from case 5 above, the C# compiler will catch it as an error. Why do I have to fix it manually if the compiler knows full well what I am trying to do?
Wouldn't the following be better?
int x = 4;
string result;
switch (x)
{
case 1:
result = "One";
case 2:
result = "A couple";
case 3:
continue; // or even goto 4
case 4:
result = "Three or four";
/*
case 5:
result = "Five"; // This would not longer be an error!! Hooray!
*/
default:
result = "Five or more";
}
Let me be clear that I am not advocating fall-through here. There is an implied break
at the end of every case
statement. The two examples are meant to be functionally equivalent.
The compiler could still yell at me if I forgot the continue
statement in case 3. This would not happen very often though and I would be happy for the help. In fact, the chance that I just missed filling in the skeleton code is pretty high in this case. Useful. Telling me that I forgot a break
statement is never helpful. It is just more busy-work to keep the compiler happy.
It seems like this is probably just a hold-over from C (which does allow you to fall through even when you have code in the case statement). Is there a deeper reason that I do not see?
I was looking at some compiler code just this morning and there were hundreds of case
statements in a switch
that did nothing but return op-codes. Every one of them had a break
statement. So much typing and clutter...
What do people think? Why is the second option not a better default?