Search code examples
c#switch-statementbreak

Can I use a switch statement without break;?


My teacher does not allow us to use things like break, goto, continue...etc I decided to add a switch statement to my code and I'm stuck because the only way I can make it work is like this:

switch (exitValidation)
{
    case 'y':
    case 'Y': exit = false; break;
    case 'n':
    case 'N': Console.WriteLine("\nPlease Enter Valid values");
              exit = false; break;
    default:  exit = true; break;
}

Is there a way to use switch without "break;"? Also, is using "break;" really that bad?


Solution

  • A solution is to extract the switch into a method an use its return value:

    public bool EvaluateSwitch(int exitValidation)
    {
        switch (exitValidation)
        {
            case 'y':
            case 'Y': return false;
            case 'n':
            case 'N': Console.WriteLine("\nPlease Enter Valid values");
                      return false;
            default:  return true; 
       }
    }