S2589 false-positive in c# switch statement

Problem identified in SonarQube Server Developer Edition 2025.4.2 and in SonarQube IDE in Rider 11.2.0.82481.

Check the following example:

public class BaseClass
{
}

public class DerivedClass : BaseClass
{
}

public static string Test(BaseClass? instance)
{
    return instance switch
    {
        DerivedClass _ => "A",
        { } => "B",
        null => "C" // S2589 is reported here
    };
}

You’ll find S2589 to be raised here. But, this is not correct. The value null is not handled in the other cases.

Hello @lg2de and thanks for reporting this.

This is not exactly a false positive, however I agree that an issue should not be raised.

The last switch arm is implicitly a discard pattern, as you are covering all the other possible cases above. If instance is not of type DerivedClass and it’s not null then it’s for sure null, thus the last arm will always be true when the execution reaches that spot.

To remove this issue you could replace the third arm with _ => "C" since we do detect discards in switch and exclude them.
Meanwhile I opened an issue in our backlog(internal only) to detect this case and not raise S2589.

thanks!