All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S2583.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

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 bool
    const bool debug = false;
    //...
    if (debug)
    {
      // Print something
    }
    
  • When the condition is the literal true or false.

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





© 2015 - 2024 Weber Informatics LLC | Privacy Policy