Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make my switch/case fall through to the next case in C#?

I'm using a switch/case statement to handle some updates for a deployed application. Basically, I want to waterfall through the cases to perform the update from the current running version to the newest version.

From Visual Studio yelling at me, I learned that C# does not allow falling through to the next case (exactly what I'm trying to do). From this question, I learned how to do what I want to do. However, it is still apparently an error.

What I've got is

switch (myCurrentVersion)
{
    case null:
    case "":
    case "0":
        UpdateToV1();
        goto case "1";
    case "1":
        UpdateToV2();
}

I'm getting the following error on the line case "1"::

Error 1 Control cannot fall through from one case label ('case "1":') to another

Am I doing something wrong? How can I force it to fall through?

like image 293
yoozer8 Avatar asked Nov 09 '11 21:11

yoozer8


People also ask

What causes fall through in switch case?

Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart …etc. It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line.

How do you break into a switch case?

You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.

How do you use goto switch case?

We can define multiple goto statements in our application to transfer the program control to the specified labeled statement. For example, we can use a goto statement in the switch statement to transfer control from one switch-case label to another or a default label based on our requirements.

Which keyword inside switch prevents fall through?

And the break keyword is used to avoid execution falling through the structure, yet sometimes that may be a useful effect.


1 Answers

You need to add a break statement even if it's the last case:

switch (myCurrentVersion)
{
    case null:
    case "":
    case "0":
        UpdateToV1();
        goto case "1";
    case "1":
        UpdateToV2();
        break;
}
like image 103
Mark Byers Avatar answered Sep 28 '22 05:09

Mark Byers