Cook Computing

Goto and C# Switch Statement

July 23, 2004 Written by Charles Cook

The C# switch statement does not allow you to drop through case blocks unless the block is empty. So how do you share the same code for more than one case? The C# Frequently Asked Questions blog provides the answer:


class Test
{
    static void Main()
    {
        int x = 3; 
        switch (x)
        {
            case 0:
                // do something
                goto case 1;
            case 1:
                // do something in common with 0
                goto default;
            default:
                // do something in common with 0, 1, and anything else
            break;
        }
    }
}

Allowing drop through for empty cases makes for readable code but is perhaps slightly inconsistent.


class Test
{
    static void Main()
    {
        int x = 3; 
        switch (x)
        {
            case 0:
            case 1:
            case 3:
                // do something in common with 0, 1, and 3
            break;
        }
    }
}