22

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

user2005549
  • 231
  • 2
  • 3
  • 4
  • This is not a duplicate of https://stackoverflow.com/questions/6696692/control-cannot-fall-through-from-one-case-label – seebiscuit Jan 09 '19 at 16:45

2 Answers2

67

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.

Brandon Gano
  • 6,430
  • 1
  • 25
  • 25
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.

Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • 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#)](https://msdn.microsoft.com/en-us/library/aa664749(v=vs.71).aspx), so `return` can be used instead of `break` in this particular case. – Alexei Levenkov Feb 05 '15 at 05:43