C#

C#

Made by DeepSource

Avoid nested ternary expressions CS-R1114

Anti-pattern
Major

The ternary operator ?: evaluates a boolean expression and returns the result of one of the two expressions, depending on whether the expression evaluates to true or false. While the ternary operator may be particularly useful in avoiding simple ifstatements, it can, however, affect the readability when nested. Therefore, it is recommended that you avoid nesting such operators.

Bad Practice

var j = i > 0 ? i * 2 : (i % 2 == 0 ? i * 3 : i * 4);

Recommended

var j = i;
if (j > 0)
{
    j = i * 2;
}
else
{
    if (i % 2 == 0)
    {
        j = i * 3;
    }
    else
    {
        j = i * 4;
    }
}