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

别来无恙 提交于 2019-12-21 07:12:09

问题


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?


回答1:


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



回答2:


This is a great example of how a poorly worded error message creates confusion. The rule of C# that is actually violated here is not that control has fallen through from one switch section to another; it is that the end point of every switch section must not be reachable. The error, by rights, should have been something like

Endpoint of switch section for case "1" must not be reachable; consider adding 'break;'

When we revisit the semantic analysis of switch statements for the Roslyn project I'll see if we can change the wording on this a bit to be more clear.

For more analysis of this and related issues, see my article on the subject.




回答3:


You don't have a break in your case "1" branch.




回答4:


put a break; after UpdateToV2();

Couldnt you get rid of the goto case "1" as it will fall through to that anyway?



来源:https://stackoverflow.com/questions/8071655/is-there-a-way-to-make-my-switch-case-fall-through-to-the-next-case-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!