Skip to content

constant-on-right

C#stylefix: safedefault: offcsharp/stylecopcsharp/roslynator

Reports a comparison with the constant on the left: null == x is x == null, 1 < x is x > 1. Without the type layer a constant is a literal, nameof, a member such as int.MaxValue, or an expression made of those; a named constant on the left is not recognised.

“Yoda” conditions came from C, where x = null by mistake compiled. In C# an assignment in a condition does not compile for a non-boolean, so the form has no protection to give, and it reads backwards: x == null says what is tested first.

To fix, swap the sides and mirror the operator. The fix is safe and does it.

Reported
...
void F(object o, int i) {
...
var g = null == o || 1 < i;
...
}
}
After the fix
...
void F(object o, int i) {
...
var g = o == null || i > 1;
...
}
}
csharp:
lint:
rules:
constant-on-right: warn # off (default), warn, error

Enabled by the presets: csharp/stylecop, csharp/roslynator.

Suppress one line with sudsy-disable-next-line constant-on-right in a comment of the file’s language.

The same check in other tools; Sudsy reports what each upstream rule reports.

Tool Rule Match
Roslynator RCS1098 full
StyleCop SA1131 full