Skip to content

Add braces to switch case #252

@thomaslevesque

Description

@thomaslevesque

The switch statement probably has the ugliest syntax in C#. The code of all cases in a switch share the same scope, which means you can't declare a variable with the same name in different cases. This is easily solved by enclosing the statements of a case in braces.

This:

switch (x)
{
    case 0:
        Foo();
        break;
    case 1:
        Bar();
        break;
}

becomes this:

switch (x)
{
    case 0:
    {
        Foo();
        break;
    }
    case 1:
    {
        Bar();
        break;
    }
}

Severity: Hidden (refactoring)
Category: Refactoring
Diagnostic Id: CC0073

I already wrote the code for it (see this branch), I'll just need to update the diagnostic id.

Currently it works on a single case; it would probably be useful to extend it to do it on all cases in the switch. Not sure if it should be a different analyzer, or if the same analyzer should produce a different diagnostic.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions