Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in C# break is required in switch loop after default case? [duplicate]

After default, control is supposed to automatically come out of switch loop. But C# requires use of a break statement? Why in C# control is not automatically coming out of switch loop after default?

The following microsoft doc say so: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch

In my code:

using System;

class Program {
static void Main() {
    Console.WriteLine("Enter a number between 1 and 10");
    int num;
    bool validity = int.TryParse(Console.ReadLine(), out num);
    if(validity==true) {
        switch(num) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:

                Console.WriteLine("You have entered {0}", num);
                break;
            default:
                Console.WriteLine("You have not entered a number between 1 and 10");
                //break; This part is commented
        }
    } 
    else {
        Console.WriteLine("Please make a valid input");
    }
}
} 

It gives me the error -

(23,5): error CS8070: Control cannot fall out of switch from final case label ('default:')

But on uncommenting the break part the code works fine.

like image 591
shiningstar Avatar asked Oct 18 '22 01:10

shiningstar


1 Answers

switch(num) {
    case 1:
        DoSomething();
    case 2:
        DoSomething2();
    case 3:
    case 4:
    case 5:
        Console.WriteLine("You have entered {0}", num);
        break;
    default:
        Console.WriteLine("You have not entered a number between 1 and 10");
        //break; This part is commented
    case 6:
        DoSomething3();
}

In above code in case 1 you want only DoSomething() or DoSomething() and go to case 2? To avoid such mistakes (forgotten break).

You can have after default block another case and you can forgot add break.

like image 92
BWA Avatar answered Oct 21 '22 05:10

BWA