dotnet / roslyn-analyzers

MIT License
1.58k stars 464 forks source link

CA1508: False positive in switch expression when conditions #7338

Open AnthonyMastrean opened 3 months ago

AnthonyMastrean commented 3 months ago

Analyzer

Diagnostic ID: CA1508: Avoid dead conditional code

Analyzer source

SDK: Built-in CA analyzers in .NET 5 SDK or later

Version: SDK 5.0.100

Describe the bug

The analyzer warns on the below code despite no condition that would indicate value is not null.

Steps To Reproduce

I'm having trouble minimizing the example, but the when condition seems to be required.

static class Ca1508FalsePositive
{
    private static bool Example(string? value) => value switch
    {
        null => false,
        not null when string.IsNullOrEmpty(value) => false, // CA1508
        not null => true, // CA1508
    };
}

This doesn't raise the warning.

static class Ca1508NoWarnings
{
    private static bool Example(string? value) => value switch
    {
        null => false,
        _ when string.IsNullOrEmpty(value) => true, // CA1508
        _ => false, // CA1508
    };
}

Expected behavior

No warnings!

Actual behavior

Warnings on both not null arms of the switch expression.

'not null when string.IsNullOrEmpty(value) => true' is always 'true'. Remove or refactor the condition(s) to avoid dead code.
'not null => false' is always 'true'. Remove or refactor the condition(s) to avoid dead code.

Additional context

Might be related to #5142