Skip to main content

NegatedTernaryCondition

Diagnostic Rule Overview

FieldValue
IDSHIMMER2010
Analyzer titleAvoid negation in ternary condition
Analyzer messageThis ternary condition has a negation
Code fix titleInvert the ternary for clarity
Default severityInfo
Minimum framework/language versionN/A
CategoryShimmeringStyle
Link to codeNegatedTernaryConditionAnalyzer.cs
Code fix exists?Yes

Detailed Explanation

Using negation (!) in a ternary condition reduces readability because it forces the reader to mentally invert the condition. Instead, swapping the order of the true/false branches often makes the code more intuitive.

Note that this diagnostic is not triggered if either of the branches or the condition contains another ternary expression.

Examples

Flagged code:

namespace Tests;
class Test
{
string Do(bool condition) => !condition ? "when false" : "when true";
}

Fixed code:

namespace Tests;
class Test
{
string Do(bool condition) => condition ? "when true" : "when false";
}

Justification of the Severity

While removing negation in the ternary condition often improves readability, this is a stylistic suggestion that is not related to performance or buggy behaviors. Some people prefer to handle common cases first, and others prefer to handle exceptional cases first, regardless of the existence of negation in the ternary condition.

When to Suppress

Suppress this diagnostic if you find the existing code more readable.