2013-01-07

C# Blooper №9: Annoying case statement fall-through rules.


Before reading any further, please read the disclaimer.

Overall, C# takes an approach which is far more friendly to novice programmers than its predecessors, C and C++ were. For example, in the case of switch statements, C# does not allow the old, error-prone style of C and C++ where you could simply fall through from one case statement to the following one; instead, at the end of each case statement C# requires either a break statement, or a goto statement to explicitly jump to another label. That's all very nice and dandy, except for one thing: C# requires a break or goto even at the last case statement of a switch statement!

namespace Test9
{
    class Test
    {
        void statement() { }

        void wtf_is_it_with_falling_through_the_last_case_label( int a )
        {
            switch( a )
            {
                case 42:
                    statement();
                    break;
                default:
                    statement();
                    break; //Need this 'break' or else: CS0163: Control cannot fall through from one case label ('default:') to another
            }
        }
    }
}

I mean, seriously, WTF?

-

No comments:

Post a Comment