Roslyn: IDE0066 (switch pattern) code fix is incorrect

Created on 24 Sep 2020  路  7Comments  路  Source: dotnet/roslyn

Version Used: 16.8.0 Preview 3.0

Steps to Reproduce:

The following snippet

switch (invocation.TargetMethod.Name)
{
    case "Last":
    case "First":
    case "Count":
        return true;
    default:
        return false;
}

gets refactored into the following form:

return invocation.TargetMethod.Name switch
{
    "Last" => true,
    _ => false,
};

which is incorrect.

Expected Behavior:

All cases are correctly converted.

Actual Behavior:

The code fix only take the first case declared.

Area-IDE Bug IDE-CodeStyle Resolution-Fixed

Most helpful comment

Doesn't repro for me either. Likely fixed at some point. Have created test to validate this is workign and will not regress.

All 7 comments

@alrz ?

Couldn't repro on master. With 8.0 it's missing and with 9.0 we correctly rewrite to or patterns.

        public async Task TestOnMultiCaseSection_String_CSharp9()
        {
            var testCode = @"
class Program
{
    bool M(string s)
    {
        [|switch|] (s)
        {
            case ""Last"":
            case ""First"":
            case ""Count"":
                return true;
            default:
                return false;
        }
    }
}";
            var fixedCode = @"
class Program
{
    bool M(string s)
    {
        return s switch
        {
            ""Last"" or ""First"" or ""Count"" => true,
            _ => false,
        };
    }
}";

            await new VerifyCS.Test
            {
                TestCode = testCode,
                FixedCode = fixedCode,
                LanguageVersion = CSharp9,
            }.RunAsync();
        }

Is it possible that the code is in error state? @Evangelink

I have reproduced the error multiple time when working on roslyn analyzers. I have just tried now and the code is compiling but still giving me the invalid code:

image

Maybe this is something that is fixed on current master of roslyn but not on the version used by the analyzer. As far as I can see we use v3.3.1 in https://github.com/dotnet/roslyn-analyzers/blob/master/eng/Versions.props#L25

And I am using VS Version 16.8.0 Preview 3.1

Doesn't repro for me either. Likely fixed at some point. Have created test to validate this is workign and will not regress.

Just for my curiosity, if you create the following snippet somewhere in the code of your preview of VS do you have the right behavior?

Was this page helpful?
0 / 5 - 0 ratings