Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control cannot fall through from one case label ('default:') to another in C# [duplicate]

Tags:

c#

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

like image 236
user2005549 Avatar asked Feb 05 '15 04:02

user2005549


2 Answers

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.

like image 54
Brandon Gano Avatar answered Sep 18 '22 13:09

Brandon Gano


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.

like image 40
Icemanind Avatar answered Sep 19 '22 13:09

Icemanind