Use a 'goto' in a switch?
C# refuses to let cases fall through implicitly (unless there is no code in the case) as in C++: you need to include break
. To explicitly fall through (or to jump to any other case) you can use goto case
. Since there is no other way to obtain this behaviour, most (sensible) coding standards will allow it.
switch(variable)
{
case 1:
case 2:
// do something for 1 and 2
goto case 3;
case 3:
case 4:
// do something for 1, 2, 3 and 4
break;
}
A realistic example (by request):
switch(typeOfPathName)
{
case "relative":
pathName = Path.Combine(currentPath, pathName);
goto case "absolute";
case "expand":
pathName = Environment.ExpandEnvironmentVariables(pathName);
goto case "absolute";
case "absolute":
using (var file = new FileStream(pathName))
{ ... }
break;
case "registry":
...
break;
}
This construct is illegal in C#:
switch (variable) {
case 2:
Console.WriteLine("variable is >= 2");
case 1:
Console.WriteLine("variable is >= 1");
}
In C++, it would run both lines if variable = 2
. It may be intentional but it's too easy to forget break;
at the end of the first case label. For this reason, they have made it illegal in C#. To mimic the fall through behavior, you will have to explicitly use goto
to express your intention:
switch (variable) {
case 2:
Console.WriteLine("variable is >= 2");
goto case 1;
case 1:
Console.WriteLine("variable is >= 1");
break;
}
That said, there are a few cases where goto
is actually a good solution for the problem. Never shut down your brain with "never use something" rules. If it were 100% useless, it wouldn't have existed in the language in the first place. Don't use goto
is a guideline; it's not a law.