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

Should not warn assigning anonymous type instance with trivial nullability differences #33577

Open cston opened 5 years ago

cston commented 5 years ago

Should not warn on the following assignments:

#nullable enable

interface IOut<out T> { }

class Program
{
    static void F1<T>(T? x, T? y) where T : struct
    {
        if (x == null) return;
        var a = new { x, y };
        var b = new { x = y, y };
        b = a; // warning: mismatch
    }

    static void F2<T>(IOut<T> x, IOut<T?> y) where T : class
    {
        var a = new { F = x };
        var b = new { F = y };
        b = a; // warning: mismatch
    }
}
jcouv commented 5 years ago

Just to clarify, this is because anonymous types are readonly, so we can treat their "type parameters" as out.

From discussion with Andy, anonymous types are not variant and there is no conversion defined.

    static void F2<T>()
    {
        var c = new  { G = new object() };
        var d = new  { G = "" };
        d = c; // error CS0029: Cannot implicitly convert type '<anonymous type: object G>' to '<anonymous type: string G>'
    }

We can't do variance on non-interface types. For nullability, we could do special-case a design, but that would need an explicit design decision from LDM.