Why is this an issue?
When switch
statements have large sets of multi-line case clauses, the code becomes hard to read and maintain.
For example, the Cognitive Complexity is going to be particularly high.
In such scenarios, it’s better to refactor the switch to only have single-line case clauses.
When all the case clauses of a switch statement are single-line, the readability of the code is not affected. Moreover,
switch statements with single-line case clauses can easily be converted into switch expressions, which are
more concise for assignment and avoid the need for break statements.
Exceptions
This rule ignores:
switchstatements overEnumarguments- fall-through cases
return,breakandthrowstatements in case clauses
How to fix it
Extract the logic of multi-line case clauses into separate methods.
Code examples
The examples below use the "Maximum number of case" property set to 4.
Note that from C# 8, you can use switch expression.
Noncompliant code example
public int MapChar(char ch, int value)
{
switch(ch) // Noncompliant
{
case 'a':
return 1;
case 'b':
return 2;
case 'c':
return 3;
// ...
case '-':
if (value > 10)
{
return 42;
}
else if (value < 5 && value > 1)
{
return 21;
}
return 99;
default:
return 1000;
}
}
Compliant solution
public int MapChar(char ch, int value)
{
switch(ch) // Compliant: All 5 cases are single line statements
{
case 'a':
return 1;
case 'b':
return 2;
case 'c':
return 3;
// ...
case '-':
return HandleDash(value);
default:
return 1000;
}
}
private int HandleDash(int value)
{
if (value > 10)
{
return 42;
}
else if (value < 5 && value > 1)
{
return 21;
}
return 99;
}
For this example, a switch expression is more concise and clear:
public int MapChar(char ch, int value) =>
ch switch // Compliant
{
'a' => 1,
'b' => 2,
'c' => 3,
// ...
'-' => HandleDash(value),
_ => 1000,
};
private int HandleDash(int value)
{
if (value > 10)
{
return 42;
}
else if (value < 5 && value > 1)
{
return 21;
}
return 99;
}
Resources
Documentation
- Sonar - Cognitive Complexity
- Microsoft Learn - The
switchstatement - Microsoft Learn - C#: Switch Expression