Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Unexpected nullability warning is reported for erroneous conditional assignment #72912

@AlekseyTs

Description

@AlekseyTs
        [Fact]
        public void Test()
        {
            string source = @"
#nullable enable

public class C
{
    public static void Main()
    {
        C2? c = null;
        var a = c ??= ""2"";
        Print(a);        
    }

    static void Print(dynamic b) 
    {
    }
}

class C2 {}
";

            var comp = CreateCompilation(source, options: TestOptions.DebugExe, targetFramework: TargetFramework.StandardAndCSharp);

            comp.VerifyDiagnostics(
                // (9,17): error CS0019: Operator '??=' cannot be applied to operands of type 'C2' and 'string'
                //         var a = c ??= "2";
                Diagnostic(ErrorCode.ERR_BadBinaryOps, @"c ??= ""2""").WithArguments("??=", "C2", "string").WithLocation(9, 17),
                // (9,23): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'C2'.
                //         var a = c ??= "2";
                Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"""2""").WithArguments("string", "C2").WithLocation(9, 23)
                );
        }

The nullability warning doesn't really make sense. The nullability actually matches, the types are different though.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions