1

I have a swith where I need to do the same procedure in equal cases. For example:

    enum Day
    {
        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
    }

    private string Do(Day day)
    {
        switch (day)
        {
            case Day.Monday:
                return "Study";
            case Day.Wednesday:
                return "Study";
            case Day.Friday:
                return "Study";
            case Day.Tuesday:
                return "Play Futbol";
            case Day.Thursday:
                return "Play Futbol";
            default: return "Party";
        }
    }

I like join the case statement where I do the same procedure. I know that a swith is like an if-else statement, but I'll want to know if exist any way to do that with the switch.

Alexander Leyva Caro
  • 1,183
  • 1
  • 12
  • 21

2 Answers2

4

Just put the cases together that you want to use the same code.

As Grant noted in the comments, it's in the documentation: http://msdn.microsoft.com/en-us/library/06tc147t.aspx

enum Day
{
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

private string Do(Day day)
{
    switch (day)
    {
        case Day.Monday:
        case Day.Wednesday:
        case Day.Friday:
            return "Study";
        case Day.Tuesday:
        case Day.Thursday:
            return "Play Futbol";
        default: 
            return "Party";
    }
}
Oliver
  • 43,366
  • 8
  • 94
  • 151
Wyatt Earp
  • 1,783
  • 13
  • 23
2

If on multiple case the same thing should be done you can simply stack these cases:

private string Do(Day day)
{
    switch (day)
    {
        case Day.Monday:
        case Day.Wednesday:
        case Day.Friday:
            return "Study";
        case Day.Tuesday:
        case Day.Thursday:
            return "Play Futbol";
        default:
            return "Party";
    }
}

If you need to do something in one case and then fall through to another case, this is not directly possible. Instead you have to write an explicitly goto case.

switch (str)
{
    case "1":
    case "small":
        cost += 25;
        break;
    case "2":
    case "medium":
        cost += 25;
        goto case "1";
    case "3":
    case "large":
        cost += 50;
        goto case "1";
    default:
        Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
        break;
}
Oliver
  • 43,366
  • 8
  • 94
  • 151