An operand of a boolean expression that never changes the result of the expression might not match the programmer’s intent and can lead to unexpected behavior and potential bugs.
var a = true;
if (a)
{
DoSomething();
}
This also applies to the null
coalescing operator when one of the operands always evaluates to null.
string d = null; var v1 = d ?? "value";
This rule will not raise an issue in either of these cases:
const bool
const bool debug = false;
//...
if (debug)
{
// Print something
}
true or false. In these cases, it is obvious the code is as intended.
The conditions should be reviewed to decide whether:
public void Sample(bool b, bool c)
{
var a = true;
if (a) // Noncompliant: "a" is always "true"
{
DoSomething();
}
if (b && a) // Noncompliant: "a" is always "true"
{
DoSomething();
}
if (c || !a) // Noncompliant: "!a" is always "false"
{
DoSomething();
}
string d = null;
var v1 = d ?? "value"; // Noncompliant: "d" is always null and v1 is always "value".
var v2 = s ?? d; // Noncompliant: "d" is always null and v2 is always equal to s.
}
The unnecessary operand is updated:
public void Sample(bool b, bool c, string s)
{
var a = IsAllowed();
if (a) // Compliant
{
DoSomething();
}
if (b && a) // Compliant
{
DoSomething();
}
if (c || !a) // Compliant
{
DoSomething();
}
string d = GetStringData();
var v1 = d ?? "value"; // Compliant
var v2 = s ?? d; // Compliant
}
The unnecessary operand is removed:
public void Sample(bool b, bool c, string s)
{
DoSomething();
if (b) // Compliant
{
DoSomething();
}
if (c) // Compliant
{
DoSomething();
}
var v1 = "value"; // Compliant
var v2 = s; // Compliant
}