Skip to content

Unexpected nullability warning is reported for erroneous conditional assignment #72912

Open

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.

Activity

  1. ghost added
    untriaged
    on Apr 6, 2024
  2. AlekseyTs commented on Apr 6, 2024

    @AlekseyTs
    ContributorAuthor
  3. added and removed
    untriaged
    on Apr 22, 2024
  4. added this to the Backlog milestone on Apr 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions