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
19.02k stars 4.03k forks source link

"Inline temporary variable" introduces an unnecessary cast that's reported as nullability issue #60552

Open Tragetaschen opened 2 years ago

Tragetaschen commented 2 years ago

Version Used: 17.2.0 Preview 2.0

Steps to Reproduce:

public class C
{
    private struct S
    {
    }

    public string M()
    {
        S s;
        var a = "" + s; // "Inline temporary variable" for a
        return a;
    }
}

Run "Inline temporary variable" for a.

Expected Behavior:

public class C
{
    private struct S
    {
    }

    public string M()
    {
        S s;
        // "Inline temporary variable" for a
        return "" + s;
    }
}

Actual Behavior:

public class C
{
    private struct S
    {
    }

    public string M()
    {
        S s;
        // "Inline temporary variable" for a
        return (string?)("" + s);
    }
}

The refactoring introduces a cast to (string?) even though neither a nor the return type were ever nullable.

On a related note: Is the comment trivia expected to stay where it is and not move to the return line?

Youssef1313 commented 2 years ago

I think this is because var has is inferred as nullable type. A fix for this may reuse helpers in #58866

CyrusNajmabadi commented 4 days ago

We would take a targeted community fix here.