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:
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
Documentation