Check for missing default case in switch statement

Viewed 3620

For ReSharper 6.1, there is no built-in inspection item for missing default statements within a switch for C#, however the custom patterns seem generally robust. I've messed around with them a bit for cases like missing else statements for if blocks, but I'm not sure how to do a check for missing default.

Here's what I have so far:

Search Pattern

switch($expr$)
{
    case $val$:
        $statement$
        break;
    $missingDefault$
}

Replacement Pattern

switch($expr$)
{
    case $val$:
        $statement$
        break;
    default:
        break;
}

Where $expr$ is an expression, $val is an expression, $statement$ is any number of statements, and $missingDefault$ is a maximum of 0 statements.

The problems here are the following:

  • We can have any number of cases, which are themselves a collection made up of one or more statements (case + break, etc.) and any number of expressions
  • For search pattern matching, we should only match against occurrences where there is nothing after the last case (ie. no default)
  • We need the 'break' in the search pattern such that we can define nonexistence of statements thereafter. This break is required by the compiler, anyway.

Obviously, this search pattern only matches against occurrences containing a single case and no default, so is relatively useless. I need a pattern that will match against switches with any number of cases, any number of which may or may not contain a break (except the last case) and can contain any number of statements, and no default.

Thanks for your help.

2 Answers
Related