All rules
CA1508Maintainability Enabled by default: No

Avoid dead conditional code

Avoid dead conditional code

Microsoft docs

Description

Methods can have conditional code, such as if statements, binary expressions (==, !=, <, >), null checks, etc. For example, consider the following code:

C# and VB compilers perform analysis of conditional checks involving compile-time _constant values_ that always evaluate to true or false. This analyzer performs data flow analysis of non-constant variables to determine redundant conditional checks involving _non-constant values_. In the preceding code, the analyzer determines that i and j are both 0 for all code paths that reach i != j check. Hence, this check will always evaluate to false at runtime. The code inside the if statement is dead code and can be removed or refactored. Similarly, the analyzer tracks nullness of variables and reports redundant null checks. This analyzer performs an expensive dataflow analysis of non-constant values. This can increase the overall compile time on certain code bases.

Cause

A method has conditional code that always evaluates to true or false at runtime. This leads to dead code in the false branch of the condition.

By default, this rule analyzes the entire codebase, but this is configurable.

Example

public void M(int i, int j)
{
    if (i != 0)
    {
        return;
    }

    if (j != 0)
    {
        return;
    }

    // Below condition will always evaluate to 'false' as 'i' and 'j' are both '0' here.
    if (i != j)
    {
        // Code in this 'if' branch is dead code.
        // It can either be removed or refactored.
        ...
    }
}

When to suppress

It's safe to suppress a violation of this rule if you're not concerned about the maintainability of your code. It is also fine to suppress violations that are identified to be false positives. These are possible in the presence of concurrent code that can execute from multiple threads.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0