Is it possible to jump from a switch statement to another switch statement without leaving the current switch in C# ?
Branching in switch statement
I don't think so. Why would you want to do this? Doesn't sound like a very good thing for code readability.
It sounds like a really bad idea to me either way.
You should be able to embed a switch in the code block of a case label if that is what you mean to do.
private void Button_Click(object sender, RoutedEventArgs e)
{
int condition = 0;
switch (condition)
{
case 0:
{
switch (condition)
{
case 0:
Console.Write("Switch in a Switch");
break;
}
}
break;
default:
break;
}
}
If you want to re-use code, just factor it out to a method and invoke it from any location that needs to (re)use the functionality.
Probably I asked the question wrong so it is misunderstood. What I actually wanted was to jump from one case statement to another case statement in one switch like:
switch(somevalue)
{
case somevalue1:
Function1();
break;
case somevalue2:
Function2();
break;
}
So for example that the code jumps from case somevalue1 to case somevalue2 without leaving the switch statement.
But in C# we must have a break I think. Anyway I would like to jump to somevalue2 without deleting the break.
What I actually wanted was to jump from one case statement to another case statement in one switch...
Yes, you can do that! And unlike the above examples, it's perfectly acceptable to do this if you want to:
switch(somevalue)
{
case somevalue1:
Function1();
goto case somevalue2;
case somevalue2:
Function2();
break;
}
It's not that bad. I haven't found myself needing to use it at all. If you find yourself needing to do it a lot, it might indicate that you should refactor the common code out into a function.