Nested Ternary
ID |
csharp.nested_ternary |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
CSharp |
Tags |
readability, simplification |
Description
Reports a ternary conditional expression cond ? a : b that contains another ternary in
its condition or in either of its arms. Only the outermost ternary of a nested group is
reported.
Rationale
Stacked ternaries are dense and easy to misread. The reader has to track multiple
conditions and branches packed into a single expression, and precedence surprises are
common. An if/else chain or a switch expression states the same logic far more
clearly.
var label = x > 0 ? (x > 10 ? "big" : "small") : "neg"; // FLAW — nested ternary
var label = x > 0 ? "pos" : "neg"; // OK — single ternary
Remediation
Rewrite the nested ternary as an if/else chain or, in modern C#, a switch
expression that pattern-matches the conditions. Both make each branch explicit and
readable.