dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
18.92k stars 4.02k forks source link

CA1854's automatic fix doesn't account for existing "value" variables #71062

Open ZacharyPatten opened 9 months ago

ZacharyPatten commented 9 months ago
Dictionary<string, object> dictionary = [];
int value = Random.Shared.Next();
if (dictionary.ContainsKey("helloworld") && dictionary["helloworld"] is string)
{
    return;
}

The above code triggers a CA1854, which is fine, but the current implementation of the automatic correction results in compilation errors because the autocorrection appears to be hard coded to declare a new variable "value" as an out parameter when a variable of the same name may already exist. Here is what it currently autocorrects to:

Dictionary<string, object> dictionary = [];
int value = Random.Shared.Next();
if (dictionary.TryGetValue("helloworld", out object? value) && value is string)
{
    return;
}

Which results in compilation error CS0128.

I don't know what the precedence is for naming new variables generated by automatic fixes, (value1, value2, value3...?), but either way we don't want compiler errors.   I confirmed this is happening in a C# project targeting net8.0 in both Visual Studio Community 2022 Preview 17.9.0 Preview 1.1 and Visual Studio Community 2022 17.8.2

related #66486 (might not be related... but both issues deal with CA1854) @mavasani

dotnet-issue-labeler[bot] commented 9 months ago

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.