182

I am trying to write a switch statement that would type the search term in the search field depending on whichever search textbox is present. I have the following code. But I am getting a "Control cannot fall through from one case label" error.

switch (searchType)
{
    case "SearchBooks":
        Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchBooks_SearchBtn']");

    case "SearchAuthors":
        Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
}

Control cannot fall through from one case label (case "SearchBooks":) to another

Control cannot fall through from one case label (case "SearchAuthors":) to another

3
  • I just realized how significantly nicer a switch statement would look if we didn't have to put break; in there. It's a horrible artifact from the past. May 4, 2021 at 19:08
  • @Simon_Weaver Sometime you do want to group several case items and treat them the same! Falling through is very nice in those cases. Aug 8, 2021 at 12:02
  • @stackoverblown definitely, but that's sort of a special case that the compiler could be smart enough to figure out. Either way we're stuck with it! Aug 8, 2021 at 21:58

8 Answers 8

317

You missed some breaks there:

switch (searchType)
{
    case "SearchBooks":
        Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
        break;

    case "SearchAuthors":
        Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
        break;
}

Without them, the compiler thinks you're trying to execute the lines below case "SearchAuthors": immediately after the lines under case "SearchBooks": have been executed, which isn't allowed in C#.

By adding the break statements at the end of each case, the program exits each case after it's done, for whichever value of searchType.

11
  • 36
    For me, I sat there looking at this code and my own until I finally realised I was actually missing the break on the very last case, for anyone who finds that helpful.
    – somoso
    Mar 23, 2013 at 12:52
  • 18
    And what if my solution requires no break because it needs to fall through on some circumstances?!
    – Black
    Oct 26, 2017 at 21:31
  • 15
    wow, what the heck were the C# devs thinking?! It works in every programming language I know, but not in C#.
    – Black
    Oct 27, 2017 at 7:05
  • 9
    The one thing this answer is missing is the fact that you can still do C-Style fall-throughs using goto case "some String".
    – NH.
    Jan 3, 2018 at 22:00
  • 7
    C# does this the right way. C# devs are geniuses. The fall-through mechanism that other languages like C++ use is a mistake. C#'s requirement of an explicit fall through via 'goto case' is safer, more powerful, and clearer. Not only can you achieve the 'fall through' behavior, you can explicitly 'fall to any case explicitly'. Falling through is a lazy joke in other languages. C# was designed to fix all this weird and error prone quirks of older languages.
    – Triynko
    Jan 3, 2020 at 13:42
155

You need to break;, throw, goto, or return from each of your case labels. In a loop you may also continue.

        switch (searchType)
        {
            case "SearchBooks":
                Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
                Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
                break;

            case "SearchAuthors":
                Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
                Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
                break;
        }

The only time this isn't true is when the case labels are stacked like this:

 case "SearchBooks": // no code inbetween case labels.
 case "SearchAuthors":
    // handle both of these cases the same way.
    break;
6
  • 8
    continue is possible as well Feb 4, 2014 at 15:09
  • 4
    Can anyone explain -why- this is? I feel like there are legitimate use cases to execute code and have control continue fall through to the next case. Feb 5, 2014 at 7:07
  • 15
    @YasharBahman, I think there are far more bugs than intended cases in languages that support case fall-through. In C#, the language allows you to goto case "SearchBooks"; so you have the ability to do what you need to do without losing much expressiveness or adding unexpected bugs.
    – agent-j
    Feb 5, 2014 at 14:08
  • 3
    @agent-j I see. Thanks, that makes a lot of sense. Also, I didn't know you could use goto like that, that's really cool! (although, I think I'll always be weary of using it since my professors have convinced me that I will spontaneously combust if I do) Feb 6, 2014 at 9:03
  • 5
    Why isn't this one the accepted answer? It tells more about what options you have for a switch statement plus giving the answer to the question. Oct 30, 2015 at 16:35
45

You can do more than just fall through in C#, but you must utilize the "dreaded" goto statement. For example:

switch (whatever)
{
  case 2:
    Result.Write( "Subscribe" );
    break;
  case 1:
    Result.Write( "Un" );
    goto case 2;
}
3
  • 1
    This seems to be the most versatile solution. Why would you call goto "dreaded" though?
    – shoopi
    Apr 3, 2021 at 14:56
  • thank you, this works when default is in the middle and you want to fall-through to the next case...
    – Ariel Yust
    Dec 8, 2021 at 16:42
  • @shoopi Because it's often implemented poorly, tangling the control structure.
    – arkon
    Mar 1, 2022 at 8:54
14

You need to add a break statement:

switch (searchType)
{
case "SearchBooks":
    Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
    break;
case "SearchAuthors":
    Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
    break;
}

This assumes that you want to either handle the SearchBooks case or the SearchAuthors - as you had written in, in a traditional C-style switch statement the control flow would have "fallen through" from one case statement to the next meaning that all 4 lines of code get executed in the case where searchType == "SearchBooks".

The compiler error you are seeing was introduced (at least in part) to warn the programmer of this potential error.

As an alternative you could have thrown an error or returned from a method.

2
  • 1
    Is there a way to replicate the C-like switch here? Run some code in one switch and then fall through to another one that will run for everyone? Jun 10, 2015 at 14:23
  • @JohnDemetriou You can use go to case statements to replicate the same.
    – itsme.cvk
    Apr 23, 2017 at 21:47
7

At the end of each switch case, just add the break-statement to resolve this problem

switch (manu)
{
    case manufacturers.Nokia:
        _phanefact = new NokiaFactory();
        break;

    case manufacturers.Samsung:
        _phanefact = new SamsungFactory();
        break;  
}
5

You missed break statements. Don't forget to use break-statements even in the default case.

switch (searchType)
{
    case "SearchBooks":
        Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
        break;
    case "SearchAuthors":
        Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
        break;
    default:
        Console.WriteLine("Default case handling");
        break;
}
4

Since it wasn't mentioned in the other answers, I'd like to add that if you want case SearchAuthors to be executed right after the first case, just like omitting the break in some other programming languages where that is allowed, you can simply use goto.

switch (searchType)
{
    case "SearchBooks":
    Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
    goto case "SearchAuthors";

    case "SearchAuthors":
    Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
    break;
}
0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Case_example_1
{
    class Program
    {
        static void Main(string[] args)
        {
            Char ch;
            Console.WriteLine("Enter a character");
            ch =Convert.ToChar(Console.ReadLine());
            switch (ch)
            {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                case 'A':
                case 'E':
                case 'I':
                case 'O':
                case 'U':

                    Console.WriteLine("Character is alphabet");
                    break;

                default:
                    Console.WriteLine("Character is constant");
                    break;

            }

            Console.ReadLine();

        }
    }
}
3
  • 1
    You should put some words or something to explain why this a solution. Since you don't explain why you need the breaks for some and not others. Oct 30, 2015 at 16:37
  • 3
    did you mean "consonant"? Feb 5, 2016 at 15:07
  • 1
    1. I think you meant "vowel" vs. "alphabet". 2. You might want to change switch (ch) to the following. char vowelCheckChar = ( (Char.ToLower(ch) == 'y') ? ( ((new Random()).Next(2) == 0) ? ch : 'a' ) : ch ); // char vowelCheckChar = switch (vowelCheckChar) Sorry, had to. ;)
    – Tom
    May 2, 2017 at 14:58

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.