Seeing how C# does not support implicit fall-though in switch statements, why use the break keyword? All the code snippets I find on the web use the break keyword. Is it just habit from other languages?

Thanks.

It's an explicit indication that it doesn't support fall-through, for people who are coming to C# from other languages.

commented: Thanks, that is what I suspected. +3

Note that you can use fall-through for empty case's:

switch(i)
{
    case 0:
    case 1:
        ...
        break;
    case 2:
        ...
        break;
}

This is occasionally useful.

It's an explicit indication that it doesn't support fall-through, for people who are coming to C# from other languages.

Thanks, that is what I suspected.

Note that you can use fall-through for empty case's:

switch(i)
{
    case 0:
    case 1:
        ...
        break;
    case 2:
        ...
        break;
}

This is occasionally useful.

I see, as a sort of do-nothing case, when the default does something. Thanks.

Not quite, it will actually fall-through, for instance:

int i = 0;
switch(i)
{
    case 0:
    case 1:
        Console.WriteLine("valid");
        break;
    default:
        Console.WriteLine("invalid");
        break;
}

This will output valid . It just allows you to have multiple discrete values for a single block of code.

Yes, nmaillet, I understand the fall-through exception for empty cases. In my reply I was referring to your use of multiple cases and then a break statement. However, in the OP I was asking why is a break statement used after a statement that would otherwise prevent fallthrough in C#.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.