Total .NET Analyzer Rule Documentation  

NoSelectDefault Rule

Consider adding a default fall through for Select Case and Switch statements.

Remarks

Select Case statements should generally have a default fall through to handle unanticipated test expression results. Without a default fall through, code that does not meet anticipated results will simply do nothing and continue execution after the Select Case statement.

The following code handles for string values of '+', '-', and '*'. However, if another value is passed (for example, '/'), the Select Case statement does nothing:


' VB
Select Case mathFunction
Case "+"
Add(num1, num2)
Case "-"
Subtract(num1, num2)
Case "*"
Multiply(num1, num2)
End Select

// C#
switch(mathFunction)
{
case "+":
Add(num1, num2);
break;
case "-":
Subtract(num1, num2);
break;
case "*":
Multiply(num1, num2);
break;
}

Resolution

You should either add default code to handle unanticipated conditions, or at a minimum, add a comment stating that the condition could not happen. In Visual Basic, use a Case Else statement. In C#, use the default keyword. For example, you could revise the code above to show an error if it encounters an unanticipated result:

' VB
Select Case mathFunction
Case "+"
Add(num1, num2)
Case "-"
Subtract(num1, num2)
Case "*"
Multiply(num1, num2)
Case Else
Console.WriteLine("Only +, -, and * are handled.")
End Select

// C#
switch(mathFunction)
{
case "+":
Add(num1, num2);
break;
case "-":
Subtract(num1, num2);
break;
case "*":
Multiply(num1, num2);
break;
default:
Console.WriteLine("Only +, -, and * are handled.");
break;
}

See Also

VB Select Case Statement

C# switch statement