Why is this an issue?
Conditional expressions which are always true or false can lead to unreachable code.
In the case below, the call of Dispose() never happens.
var a = false;
if (a)
{
Dispose(); // Never reached
}
Exceptions
This rule will not raise an issue in either of these cases:
- When the condition is a single
const boolconst bool debug = false; //... if (debug) { // Print something } - When the condition is the literal
trueorfalse.
In these cases, it is obvious the code is as intended.
How to fix it
The conditions should be reviewed to decide whether:
- to update the condition or
- to remove the condition.
Code examples
Noncompliant code example
public void Sample(bool b)
{
bool a = false;
if (a) // Noncompliant: The true branch is never reached
{
DoSomething(); // Never reached
}
if (!a || b) // Noncompliant: "!a" is always "true" and the false branch is never reached
{
DoSomething();
}
else
{
DoSomethingElse(); // Never reached
}
var c = "xxx";
var res = c ?? "value"; // Noncompliant: c is always not null, "value" is never used
}
Compliant solution
public void Sample(bool b)
{
bool a = false;
if (Foo(a)) // Condition was updated
{
DoSomething();
}
if (b) // Parts of the condition were removed.
{
DoSomething();
}
else
{
DoSomethingElse();
}
var c = "xxx";
var res = c; // ?? "value" was removed
}
Resources
- CWE - CWE-570 - Expression is Always False
- CWE - CWE-571 - Expression is Always True
- Wikipedia - Unreachable code
Documentation
- Microsoft Learn - Conditional logical AND operator &&
- Microsoft Learn - Conditional logical OR operator ||
- Microsoft Learn - ?? and ??= operators - the null-coalescing operators