Alex Rivera | Logout

Why the c# compiler requires the break statement in switch construction?

Asked 2010-03-02T13:07:15.040
13

I'm having hard time understanding, why the compiler requires using break statement. It's not possible to miss it since the fall through is now allowed. I see the reason for the break in C or C++, but is it needed here.

Why it's not a built-in behavior to break after a case is over ? Isn't it just a syntax with no semantic?

Sorry, if it's a stupid question.

EDIT: The fall through is allowed only when the case is empty. When there is a statement there you can't omit the break statement. So, it's a different matter.

Edit
Report

1 Answer

0

Usually this kind of code is a bug:

// Contrived calculator demostration
decimal x = 5m;
decimal y = 10m;
decimal result = 0m;
string blah = "Divide";

// .. other code omitted

switch(blah) {
    case "Divide":
        result = x / y;

    case "Multiply":
        result = x * y;

    case "Add":
        result = x + y;

    case "Subtract":
        result = x - y;

    default:
        MessageBox.Show("Not a valid operation");

}

However, the compiler can't assume the missing breaks are a bug. As far as it knows, you really did want the cases to fall-through.

Simply assuming that breaks should be at the end of every case would just trade one bug for a different bug.

So, instead, the language designers disallowed fall-through from non-empty cases and throw an error if you omit them.

If you need code shared between non-empty cases, put it in a private (possibly static) method and call it from there.

One last note: Empty cases falling through is all that an empty case is expected to do, which is why it's allowed.

answered 2010-03-02T15:15:10.573

Your Answer