Question

Usually I will implement switch case in a method that return particular object. Something like below:

private string testing(string input){
    switch(input)
    {
        case "a":
        {
            ....
            return "TestingResult";
        }
        case "b":
        {
            ....
            return "TestingResultB";
        }
        default:
            return null;
    }
}

Now I'm wondering if it's possible to write a switch case for value assignment purpose? Something like below:

private string testing(string input){
    string TEST="";
    switch(input)
    {
        case "a":
        {
            ....
            TEST = "TestingResult";
        }
        case "b":
        {
            ....
            TEST = "TestingResultB";
        }
        default:
    }
    return TEST;
}

Of cause it can be achieve by simple If-Else statement, this question is for me to understand more functionality of switch case

Of course, after testing it, I receive error

control cannot fall through from one case label('case: "a"') to another
Was it helpful?

Solution 2

Yes you can. You just have to remember to put a 'jump' statement of some kind (this includes break, goto case, return, or throw), after each case label:

private string testing(string input){
    string TEST="";
    switch(input)
    {
        case "a":
            TEST = "TestingResult";
            break;
        case "b":
            TEST = "TestingResultB";
            break;
    }
    return TEST;
}

Note, the braces here are unnecessary, and the default isn't required in this construction as it will fall through the switch block if it doesn't match any of the cases.

Further Reading

OTHER TIPS

You need to add break; in each case

private string testing(string input){
    string TEST="";
    switch(input)
    {
        case "a":
            TEST = "TestingResult";
            break;
        case "b":
            TEST = "TestingResultB";
            break;
        default:
    }
    return TEST;
}

As others have mentioned, the braces within each case are unnecessary.

What you've written is perfectly legitimate, however there is no point doing the value assignment unless you are going to carry on and do some further operations with it before returning.

To help you with becoming more proficient with switch/case statements:

  • in your first example you don't need the default, just have a final return at the end of the function
  • in your second example, you don't need the default at all - you do nothing with it
  • a switch/case is usually used for multiple options, for example 4 or more. Any less than that and an if/else is equally readable. You should also bear in mind that a switch/case can give you good speed improvements in some cases
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top