24

I am having trouble with the following code it seems that the break statement is good but I could not be seeing something.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Switch
{
class swtich
{
    static void Main(string[] args)
    {
        string input; int num;
        Console.WriteLine("Enter a number from 0-6: ");
        input = Console.ReadLine();
        num = int.Parse(input);
        switch (num)
        {
            case 0:
                Console.WriteLine("Sunday");
                break;
            case 1:
                Console.WriteLine("Monday");
                break;
            case 2:
                Console.WriteLine("Tuesday");
                break;
            case 3:
                Console.WriteLine("Wednesday");
                break;
            case 4:
                Console.WriteLine("Thursday");
                break;
            case 5:
                Console.WriteLine("Friday");
                break;
            case 6:
                Console.WriteLine("Saturday");
                break;
            default:
                Console.WriteLine("Invalid input");
        }
    }
}
}

this is the error I am getting Control cannot fall through from one case label ('default:') to another

1

2 Answers 2

69

Put a break; after your default: case.

...
  case 6:
    Console.WriteLine("Saturday");
    break;
  default:
    Console.WriteLine("Invalid input");
    break;
}

The default case isn't required to be at the end, so you have to include a break just like everywhere else to avoid this warning.

1
  • oh thanks I forgot about that one Feb 5, 2015 at 4:50
26

Unlike the switch statements in C, C++ or Java, C# does not allow case statements to fall through, This includes the default case statement. You must add break after your default case.

default:
    Console.WriteLine("Invalid Input");
    break; // this is required

As @AlexeiLevenkov pointed out, break isn't necessarily required, however, some kind of statement that prevents reaching the end of the construct is required, such as return, break or goto case.

1
  • 6
    Note that "break" is not required to be part of the block - any construct that prevents reaching end of the block (like return) would do as covered in specification - The switch statement (C#), so return can be used instead of break in this particular case. Feb 5, 2015 at 5:43

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