Branching in switch statement

Started by
35 comments, last by wack 10 years, 2 months ago

Is it possible to jump from a switch statement to another switch statement without leaving the current switch in C# ?

Advertisement

I don't think so. Why would you want to do this? Doesn't sound like a very good thing for code readability.

No. If you jump to another switch, you will leave your current switch by definition. And you won't be able to jump back because two switch statements cannot both contain labels that are in scope of the other.

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;
            }
        }

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

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;
}

I didn't know that. It looks like an old basic code smile.png. Is this a good coding practice ?

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.

I was building a finite state machine where I don't need a while statement but instead I just needed to switch to another state right after the first one finished.

How would you transform the current code to put it out in a function ?

This topic is closed to new replies.

Advertisement