No Double Operators

ID

csharp.no_double_operators

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

reliability, suspicious-operator

Description

Reports doubled unary ! or ~ operators (!!x and ~~x). Both forms are no-ops: !!x on a bool simply yields x again, and ~~x on an integral type yields x. The doubled operator is almost always a typo or copy-paste error rather than intentional code.

Rationale

Some languages use !!x as an idiom to coerce a value to a boolean, but C# already has strict boolean typing so the trick has no semantic effect. The most common cause of !!x is therefore a copy-paste or fast-typing mistake.

if (!!ready)        // FLAW — equivalent to `if (ready)`
{
    Start();
}

int mask = ~~flags; // FLAW — `mask == flags`

if (!ready) { /* ... */ }  // OK
int mask2 = ~flags;        // OK

Remediation

Drop one of the operators. If you want a value forced to boolean, just use the value directly; if you want a bitwise complement, use ~ once.